@causyne/agent 1.20.76 → 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.
@@ -0,0 +1,35 @@
1
+ export interface VisualEvidenceResult {
2
+ readonly ok: boolean;
3
+ readonly required: boolean;
4
+ readonly reason?: string;
5
+ }
6
+
7
+ export interface ObservedToolOutcome {
8
+ tool?: string;
9
+ success?: boolean;
10
+ observedImage?: boolean;
11
+ }
12
+
13
+ /** A rendered DOM is not proof that a user-requested 3D scene was visually inspected. */
14
+ export function inspect3DVisualEvidence(
15
+ prompt: string,
16
+ outcomes: readonly ObservedToolOutcome[] = []
17
+ ): VisualEvidenceResult {
18
+ const text = String(prompt || '');
19
+ const needs3DVisual = /\b(?:build|create|make|design|render|implement)\b[^\n]{0,150}\b(?:3[ -]?d|three\.?js|webgl)\b/i.test(text);
20
+ if (!needs3DVisual) return { ok: true, required: false };
21
+ // The host observer sets observedImage only when image bytes actually reached
22
+ // a vision-capable provider. A file named screenshot.png or a browser
23
+ // snapshot does not satisfy this condition.
24
+ const latestMutation = outcomes.findLastIndex(item => item?.success === true &&
25
+ /^(fs_write|fs_edit|MultiEdit|write_file|edit_file)$/i.test(String(item.tool || '')));
26
+ const afterMutation = latestMutation < 0 ? outcomes : outcomes.slice(latestMutation + 1);
27
+ if (afterMutation.some(item => item?.success === true && item?.observedImage === true)) {
28
+ return { ok: true, required: true };
29
+ }
30
+ return {
31
+ ok: false,
32
+ required: true,
33
+ reason: 'The user requested a Three.js/WebGL 3D deliverable, but no rendered image was actually inspected by a vision-capable model after the last change. A browser preview or DOM snapshot alone does not verify the 3D result. Report the scene as visually unverified, or capture and inspect an image before claiming completion.'
34
+ };
35
+ }
@@ -1,41 +1,159 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import os from 'os';
4
-
5
- export const fsWrite = {
6
- schema: {
7
- name: 'fs.write',
8
- description: 'Create or overwrite a file with content using Zero-Corruption Atomic Swap. Guarantees safe file writing.',
9
- parameters: {
10
- type: 'object',
11
- properties: {
12
- path: { type: 'string' },
13
- content: { type: 'string' },
14
- createDirectories: { type: 'boolean' }
15
- },
16
- required: ['path', 'content']
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ function expandHome(value) {
6
+ return value === '~' ? os.homedir()
7
+ : value.startsWith('~/') || value.startsWith('~\\')
8
+ ? path.join(os.homedir(), value.slice(2))
9
+ : value;
10
+ }
11
+ function inside(root, target) {
12
+ const relative = path.relative(root, target);
13
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`)
14
+ && !path.isAbsolute(relative));
15
+ }
16
+ async function physicalTarget(target) {
17
+ // Resolves symlinks in the longest existing ancestor, including a symlinked
18
+ // parent of a new file. It is not a substitute for OS-level isolation.
19
+ let current = target;
20
+ const missing = [];
21
+ while (true) {
22
+ try {
23
+ const resolved = await fs.realpath(current);
24
+ return path.join(resolved, ...missing.reverse());
25
+ }
26
+ catch (error) {
27
+ if (error?.code !== 'ENOENT')
28
+ throw error;
29
+ const parent = path.dirname(current);
30
+ if (parent === current)
31
+ throw new Error('Could not resolve target ancestry');
32
+ missing.push(path.basename(current));
33
+ current = parent;
34
+ }
35
+ }
36
+ }
37
+ async function checkScope(target, context) {
38
+ if (!context || context.grantAllAccess === true)
39
+ return;
40
+ const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
41
+ ? context.workspacePaths
42
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter((value) => typeof value === 'string' && value.length > 0);
43
+ if (roots.length === 0)
44
+ return;
45
+ const physical = await physicalTarget(target);
46
+ for (const root of roots) {
47
+ try {
48
+ const resolvedRoot = await fs.realpath(path.resolve(expandHome(root)));
49
+ if (inside(resolvedRoot, physical))
50
+ return;
51
+ }
52
+ catch { /* A non-existent authorized root is not permission to escape. */ }
17
53
  }
18
- },
19
- async execute(args) {
20
- try {
21
- const target = args.path.replace(/^~\//, os.homedir() + '/');
22
-
23
- if (args.createDirectories !== false) {
24
- await fs.mkdir(path.dirname(target), { recursive: true });
25
- }
26
-
27
- // Phase 4 AGI Upgrade: Atomic File Swap
28
- // Prevent zero-byte file corruption if Node crashes during a huge write.
29
- const tempPath = `${target}.causyne_tmp_${Date.now()}`;
30
-
31
- await fs.writeFile(tempPath, args.content, 'utf8');
32
-
33
- // Atomic rename (POSIX standard guarantee)
34
- await fs.rename(tempPath, target);
35
-
36
- return { success: true, output: `Atomically wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${args.path}` };
37
- } catch (e) {
38
- return { success: false, error: `Atomic Write Failed: ${e.message}` };
54
+ throw new Error(`Target resolves outside the selected workspace: ${target}`);
55
+ }
56
+ function writeError(error, target) {
57
+ const code = error?.code;
58
+ if (code === 'EISDIR' || code === 'ENOTEMPTY') {
59
+ return `Cannot write file: "${target}" is an existing directory. Supply a filename inside it, such as ${path.join(target, 'index.html')}.`;
60
+ }
61
+ return `Atomic file write failed: ${error instanceof Error ? error.message : String(error)}`;
62
+ }
63
+ export const fsWrite = {
64
+ schema: {
65
+ name: 'fs.write',
66
+ description: 'Write a complete UTF-8 file using atomic rename. Path must be a file, not a directory.',
67
+ parameters: {
68
+ type: 'object',
69
+ properties: {
70
+ path: { type: 'string' },
71
+ content: { type: 'string' },
72
+ createDirectories: { type: 'boolean' }
73
+ },
74
+ required: ['path', 'content']
75
+ }
76
+ },
77
+ async execute(args, context) {
78
+ if (!args || typeof args.path !== 'string' || !args.path.trim()) {
79
+ return { success: false, error: 'fs_write requires a nonempty path pointing to a FILE.' };
80
+ }
81
+ if (typeof args.content !== 'string') {
82
+ return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
83
+ }
84
+ if (args.path.endsWith('/') || args.path.endsWith('\\')) {
85
+ return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
86
+ }
87
+ const target = path.resolve(expandHome(args.path.trim()));
88
+ let temporary = '';
89
+ try {
90
+ await checkScope(target, context);
91
+ let originalMode;
92
+ try {
93
+ const stat = await fs.lstat(target);
94
+ if (stat.isDirectory()) {
95
+ 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')}").` };
96
+ }
97
+ if (stat.isSymbolicLink()) {
98
+ return { success: false, error: `Refusing to replace symbolic link ${target}; use a regular file in the selected workspace.` };
99
+ }
100
+ if (!stat.isFile()) {
101
+ return { success: false, error: `Target ${target} is not a regular file.` };
102
+ }
103
+ originalMode = stat.mode & 0o777;
104
+ }
105
+ catch (error) {
106
+ if (error?.code !== 'ENOENT')
107
+ throw error;
108
+ }
109
+ if (args.createDirectories !== false) {
110
+ await fs.mkdir(path.dirname(target), { recursive: true });
111
+ }
112
+ // Re-check after creating parents: an existing parent might be a symlink.
113
+ await checkScope(target, context);
114
+ temporary = path.join(path.dirname(target), `.${path.basename(target)}.causyne-${randomUUID()}.tmp`);
115
+ const file = await fs.open(temporary, 'wx', originalMode ?? 0o600);
116
+ try {
117
+ await file.writeFile(args.content, { encoding: 'utf8' });
118
+ await file.sync();
119
+ }
120
+ finally {
121
+ await file.close();
122
+ }
123
+ // Never reinterpret a directory as a file if the destination changed.
124
+ const destinationStat = await fs.lstat(target).catch((error) => {
125
+ if (error.code === 'ENOENT')
126
+ return null;
127
+ throw error;
128
+ });
129
+ if (destinationStat && !destinationStat.isFile()) {
130
+ throw new Error(`Destination is no longer a regular file: ${target}`);
131
+ }
132
+ await checkScope(target, context);
133
+ await fs.rename(temporary, target);
134
+ temporary = '';
135
+ // Flushing the parent directory is best effort: some platforms disallow it.
136
+ try {
137
+ const directory = await fs.open(path.dirname(target), 'r');
138
+ try {
139
+ await directory.sync();
140
+ }
141
+ finally {
142
+ await directory.close();
143
+ }
144
+ }
145
+ catch { /* Do not claim crash-durable guarantees on unsupported FS. */ }
146
+ return {
147
+ success: true,
148
+ output: `Wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${target}`
149
+ };
150
+ }
151
+ catch (error) {
152
+ return { success: false, error: writeError(error, target) };
153
+ }
154
+ finally {
155
+ if (temporary)
156
+ await fs.unlink(temporary).catch(() => { });
157
+ }
39
158
  }
40
- }
41
159
  };
@@ -0,0 +1,169 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ export interface FsWriteArgs {
7
+ path: string;
8
+ content: string;
9
+ createDirectories?: boolean;
10
+ }
11
+
12
+ export interface FsWriteContext {
13
+ workspaceRoot?: string;
14
+ workspacePaths?: string[];
15
+ grantAllAccess?: boolean;
16
+ parentLoop?: { workspaceRoot?: string };
17
+ }
18
+
19
+ export interface FsWriteResult {
20
+ success: boolean;
21
+ output?: string;
22
+ error?: string;
23
+ }
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
+
83
+ export const fsWrite = {
84
+ schema: {
85
+ name: 'fs.write',
86
+ description: 'Write a complete UTF-8 file using atomic rename. Path must be a file, not a directory.',
87
+ parameters: {
88
+ type: 'object',
89
+ properties: {
90
+ path: { type: 'string' },
91
+ content: { type: 'string' },
92
+ createDirectories: { type: 'boolean' }
93
+ },
94
+ required: ['path', 'content']
95
+ }
96
+ },
97
+
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;
114
+ try {
115
+ const stat = await fs.lstat(target);
116
+ if (stat.isDirectory()) {
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.` };
121
+ }
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;
128
+ }
129
+
130
+ if (args.createDirectories !== false) {
131
+ await fs.mkdir(path.dirname(target), { recursive: true });
132
+ }
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(() => {});
167
+ }
168
+ }
169
+ };
@@ -331,6 +331,21 @@ export function repairJsonArguments(rawInput) {
331
331
  }
332
332
  }
333
333
  catch (err) {
334
+ const trimmed = trimExtraneousTrailingJsonTokens(healed);
335
+ if (trimmed !== healed) {
336
+ try {
337
+ const parsed = JSON.parse(trimmed);
338
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
339
+ return { args: parsed, repaired: true, repairs: [...repairs, 'Trimmed extraneous trailing tokens'] };
340
+ }
341
+ if (Array.isArray(parsed)) {
342
+ return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
343
+ }
344
+ }
345
+ catch {
346
+ // Fall through to error
347
+ }
348
+ }
334
349
  const errorMsg = err instanceof Error ? err.message : String(err);
335
350
  return {
336
351
  args: {},
@@ -342,22 +357,65 @@ export function repairJsonArguments(rawInput) {
342
357
  return { args: {}, repaired: false, repairs };
343
358
  }
344
359
  /**
345
- * Handle unescaped newlines/tabs inside string literals without breaking valid JSON escapes.
360
+ * Trim extraneous trailing braces, brackets, or tokens after the root JSON object/array closes.
361
+ */
362
+ function trimExtraneousTrailingJsonTokens(input) {
363
+ const str = input.trim();
364
+ if (!str.startsWith('{') && !str.startsWith('['))
365
+ return input;
366
+ let depth = 0;
367
+ let inString = false;
368
+ let escapeNext = false;
369
+ for (let i = 0; i < str.length; i++) {
370
+ const char = str[i] ?? '';
371
+ if (escapeNext) {
372
+ escapeNext = false;
373
+ continue;
374
+ }
375
+ if (char === '\\') {
376
+ escapeNext = true;
377
+ continue;
378
+ }
379
+ if (char === '"') {
380
+ inString = !inString;
381
+ continue;
382
+ }
383
+ if (inString)
384
+ continue;
385
+ if (char === '{' || char === '[') {
386
+ depth++;
387
+ }
388
+ else if (char === '}' || char === ']') {
389
+ depth--;
390
+ if (depth === 0) {
391
+ return str.slice(0, i + 1);
392
+ }
393
+ }
394
+ }
395
+ return input;
396
+ }
397
+ /**
398
+ * Handle unescaped newlines/tabs and invalid backslash escapes inside string literals without breaking valid JSON escapes.
346
399
  */
347
400
  function sanitizeUnescapedStringLiterals(input) {
348
401
  let result = '';
349
402
  let inString = false;
350
403
  let escapeNext = false;
404
+ const validEscapes = new Set(['"', '\\', '/', 'b', 'f', 'n', 'r', 't', 'u']);
351
405
  for (let i = 0; i < input.length; i++) {
352
- const char = input[i];
406
+ const char = input[i] ?? '';
353
407
  if (escapeNext) {
354
- result += char;
408
+ if (validEscapes.has(char)) {
409
+ result += '\\' + char;
410
+ }
411
+ else {
412
+ result += '\\\\' + char;
413
+ }
355
414
  escapeNext = false;
356
415
  continue;
357
416
  }
358
417
  if (char === '\\') {
359
418
  escapeNext = true;
360
- result += char;
361
419
  continue;
362
420
  }
363
421
  if (char === '"') {
@@ -381,6 +439,9 @@ function sanitizeUnescapedStringLiterals(input) {
381
439
  }
382
440
  result += char;
383
441
  }
442
+ if (escapeNext) {
443
+ result += '\\\\';
444
+ }
384
445
  return result;
385
446
  }
386
447
  /**
@@ -404,7 +465,7 @@ function balanceTruncatedJson(input, repairs) {
404
465
  let inString = false;
405
466
  let escapeNext = false;
406
467
  for (let i = 0; i < str.length; i++) {
407
- const char = str[i];
468
+ const char = str[i] ?? '';
408
469
  if (escapeNext) {
409
470
  escapeNext = false;
410
471
  continue;
@@ -375,6 +375,20 @@ export function repairJsonArguments(rawInput: unknown): RepairResult {
375
375
  return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
376
376
  }
377
377
  } catch (err: unknown) {
378
+ const trimmed = trimExtraneousTrailingJsonTokens(healed);
379
+ if (trimmed !== healed) {
380
+ try {
381
+ const parsed = JSON.parse(trimmed);
382
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
383
+ return { args: parsed as Record<string, unknown>, repaired: true, repairs: [...repairs, 'Trimmed extraneous trailing tokens'] };
384
+ }
385
+ if (Array.isArray(parsed)) {
386
+ return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
387
+ }
388
+ } catch {
389
+ // Fall through to error
390
+ }
391
+ }
378
392
  const errorMsg = err instanceof Error ? err.message : String(err);
379
393
  return {
380
394
  args: {},
@@ -388,25 +402,65 @@ export function repairJsonArguments(rawInput: unknown): RepairResult {
388
402
  }
389
403
 
390
404
  /**
391
- * Handle unescaped newlines/tabs inside string literals without breaking valid JSON escapes.
405
+ * Trim extraneous trailing braces, brackets, or tokens after the root JSON object/array closes.
406
+ */
407
+ function trimExtraneousTrailingJsonTokens(input: string): string {
408
+ const str = input.trim();
409
+ if (!str.startsWith('{') && !str.startsWith('[')) return input;
410
+ let depth = 0;
411
+ let inString = false;
412
+ let escapeNext = false;
413
+ for (let i = 0; i < str.length; i++) {
414
+ const char = str[i] ?? '';
415
+ if (escapeNext) {
416
+ escapeNext = false;
417
+ continue;
418
+ }
419
+ if (char === '\\') {
420
+ escapeNext = true;
421
+ continue;
422
+ }
423
+ if (char === '"') {
424
+ inString = !inString;
425
+ continue;
426
+ }
427
+ if (inString) continue;
428
+ if (char === '{' || char === '[') {
429
+ depth++;
430
+ } else if (char === '}' || char === ']') {
431
+ depth--;
432
+ if (depth === 0) {
433
+ return str.slice(0, i + 1);
434
+ }
435
+ }
436
+ }
437
+ return input;
438
+ }
439
+
440
+ /**
441
+ * Handle unescaped newlines/tabs and invalid backslash escapes inside string literals without breaking valid JSON escapes.
392
442
  */
393
443
  function sanitizeUnescapedStringLiterals(input: string): string {
394
444
  let result = '';
395
445
  let inString = false;
396
446
  let escapeNext = false;
447
+ const validEscapes = new Set(['"', '\\', '/', 'b', 'f', 'n', 'r', 't', 'u']);
397
448
 
398
449
  for (let i = 0; i < input.length; i++) {
399
- const char = input[i];
450
+ const char = input[i] ?? '';
400
451
 
401
452
  if (escapeNext) {
402
- result += char;
453
+ if (validEscapes.has(char)) {
454
+ result += '\\' + char;
455
+ } else {
456
+ result += '\\\\' + char;
457
+ }
403
458
  escapeNext = false;
404
459
  continue;
405
460
  }
406
461
 
407
462
  if (char === '\\') {
408
463
  escapeNext = true;
409
- result += char;
410
464
  continue;
411
465
  }
412
466
 
@@ -434,6 +488,10 @@ function sanitizeUnescapedStringLiterals(input: string): string {
434
488
  result += char;
435
489
  }
436
490
 
491
+ if (escapeNext) {
492
+ result += '\\\\';
493
+ }
494
+
437
495
  return result;
438
496
  }
439
497
 
@@ -460,7 +518,7 @@ function balanceTruncatedJson(input: string, repairs: string[]): string {
460
518
  let escapeNext = false;
461
519
 
462
520
  for (let i = 0; i < str.length; i++) {
463
- const char = str[i];
521
+ const char = str[i] ?? '';
464
522
  if (escapeNext) {
465
523
  escapeNext = false;
466
524
  continue;