@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 70 lines 2.43 KB
Raw
1 import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";
2
3 export type PendingModifier = "ctrl" | "meta";
4 export type HostPlatform = "mac" | "linux" | "windows" | "unknown";
5
6 export type ModifiedTerminalInput =
7 | { readonly kind: "write"; readonly data: string }
8 | { readonly kind: "paste" };
9
10 const UNSAFE_PASTE_BYTES = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
11
12 function applyCtrlModifier(input: string): string {
13 const firstCharacter = input[0];
14 if (!firstCharacter) {
15 return input;
16 }
17
18 const lowerCharacter = firstCharacter.toLowerCase();
19 if (lowerCharacter >= "a" && lowerCharacter <= "z") {
20 return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);
21 }
22
23 if (firstCharacter === "@") return "\u0000";
24 if (firstCharacter === "[") return "\u001b";
25 if (firstCharacter === "\\") return "\u001c";
26 if (firstCharacter === "]") return "\u001d";
27 if (firstCharacter === "^") return "\u001e";
28 if (firstCharacter === "_") return "\u001f";
29 if (firstCharacter === "?") return "\u007f";
30
31 return input;
32 }
33
34 /** Use the device clipboard for host paste chords; forwarding Ctrl+V to PowerShell pastes the host clipboard. */
35 export function resolveModifiedTerminalInput(input: {
36 readonly data: string;
37 readonly modifier: PendingModifier;
38 readonly hostPlatform: HostPlatform;
39 }): ModifiedTerminalInput {
40 const pasteModifier: PendingModifier = input.hostPlatform === "mac" ? "meta" : "ctrl";
41 if (input.modifier === pasteModifier && input.data.toLowerCase() === "v") {
42 return { kind: "paste" };
43 }
44
45 if (
46 input.data.length === 3 &&
47 input.data.startsWith("\u001b[") &&
48 /[ABCD]/.test(input.data.charAt(2))
49 ) {
50 return { kind: "write", data: `\u001b[1;${input.modifier === "ctrl" ? 5 : 3}${input.data[2]}` };
51 }
52
53 return {
54 kind: "write",
55 data: input.modifier === "ctrl" ? applyCtrlModifier(input.data) : `\u001b${input.data}`,
56 };
57 }
58
59 /** No DECSET 2004 state, so omit bracket markers. Strip unsafe controls and use CR; raw-mode TUIs read LF as Ctrl+J. */
60 export function encodeTerminalPaste(text: string): string {
61 return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");
62 }
63
64 /** Returns null for unknown OSes so callers can try weaker signals. */
65 export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {
66 if (os === "darwin") return "mac";
67 if (os === "linux") return "linux";
68 if (os === "windows") return "windows";
69 return null;
70 }