Skip to content

Commit c54b390

Browse files
authored
fix: parse escape sequences in pty_write input (#4)
The pty_write tool was receiving escape sequences like \x03 as literal strings instead of converting them to actual bytes. This meant sending Ctrl+C (\x03) would write the 4 characters '\x03' instead of the interrupt signal byte. Added parseEscapeSequences() function that converts: - \xNN to hex bytes (e.g., \x03 → Ctrl+C) - \uNNNN to unicode characters - \n, \r, \t to their respective control characters - \\\\ to literal backslash This fixes the documented behavior in write.txt which promises escape sequence support.
1 parent 98d457a commit c54b390

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/plugin/pty/tools/write.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,28 @@ import { manager } from "../manager.ts";
33
import { checkCommandPermission } from "../permissions.ts";
44
import DESCRIPTION from "./write.txt";
55

6+
/**
7+
* Parse escape sequences in a string to their actual byte values.
8+
* Handles: \n, \r, \t, \xNN (hex), \uNNNN (unicode), \\
9+
*/
10+
function parseEscapeSequences(input: string): string {
11+
return input.replace(/\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|[nrt\\])/g, (match, seq: string) => {
12+
if (seq.startsWith("x")) {
13+
return String.fromCharCode(parseInt(seq.slice(1), 16));
14+
}
15+
if (seq.startsWith("u")) {
16+
return String.fromCharCode(parseInt(seq.slice(1), 16));
17+
}
18+
switch (seq) {
19+
case "n": return "\n";
20+
case "r": return "\r";
21+
case "t": return "\t";
22+
case "\\": return "\\";
23+
default: return match;
24+
}
25+
});
26+
}
27+
628
function extractCommands(data: string): string[] {
729
const commands: string[] = [];
830
const lines = data.split(/[\n\r]+/);
@@ -38,15 +60,18 @@ export const ptyWrite = tool({
3860
throw new Error(`Cannot write to PTY '${args.id}' - session status is '${session.status}'.`);
3961
}
4062

41-
const commands = extractCommands(args.data);
63+
// Parse escape sequences to actual bytes
64+
const parsedData = parseEscapeSequences(args.data);
65+
66+
const commands = extractCommands(parsedData);
4267
for (const commandLine of commands) {
4368
const { command, args: cmdArgs } = parseCommand(commandLine);
4469
if (command) {
4570
await checkCommandPermission(command, cmdArgs);
4671
}
4772
}
4873

49-
const success = manager.write(args.id, args.data);
74+
const success = manager.write(args.id, parsedData);
5075
if (!success) {
5176
throw new Error(`Failed to write to PTY '${args.id}'.`);
5277
}

0 commit comments

Comments
 (0)