-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive-shell.ts
More file actions
196 lines (179 loc) · 4.67 KB
/
interactive-shell.ts
File metadata and controls
196 lines (179 loc) · 4.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/**
* Interactive Shell Commands Extension
*
* Enables running interactive commands (vim, git rebase -i, htop, etc.)
* with full terminal access. The TUI suspends while they run.
*
* Usage:
* pi -e examples/extensions/interactive-shell.ts
*
* !vim file.txt # Auto-detected as interactive
* !i any-command # Force interactive mode with !i prefix
* !git rebase -i HEAD~3
* !htop
*
* Configuration via environment variables:
* INTERACTIVE_COMMANDS - Additional commands (comma-separated)
* INTERACTIVE_EXCLUDE - Commands to exclude (comma-separated)
*
* Note: This only intercepts user `!` commands, not agent bash tool calls.
* If the agent runs an interactive command, it will fail (which is fine).
*/
import { spawnSync } from "node:child_process";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
// Default interactive commands - editors, pagers, git ops, TUIs
const DEFAULT_INTERACTIVE_COMMANDS = [
// Editors
"vim",
"nvim",
"vi",
"nano",
"emacs",
"pico",
"micro",
"helix",
"hx",
"kak",
// Pagers
"less",
"more",
"most",
// Git interactive
"git commit",
"git rebase",
"git merge",
"git cherry-pick",
"git revert",
"git add -p",
"git add --patch",
"git add -i",
"git add --interactive",
"git stash -p",
"git stash --patch",
"git reset -p",
"git reset --patch",
"git checkout -p",
"git checkout --patch",
"git difftool",
"git mergetool",
// System monitors
"htop",
"top",
"btop",
"glances",
// File managers
"ranger",
"nnn",
"lf",
"mc",
"vifm",
// Git TUIs
"tig",
"lazygit",
"gitui",
// Fuzzy finders
"fzf",
"sk",
// Remote sessions
"ssh",
"telnet",
"mosh",
// Database clients
"psql",
"mysql",
"sqlite3",
"mongosh",
"redis-cli",
// Kubernetes/Docker
"kubectl edit",
"kubectl exec -it",
"docker exec -it",
"docker run -it",
// Other
"tmux",
"screen",
"ncdu",
];
function getInteractiveCommands(): string[] {
const additional =
process.env.INTERACTIVE_COMMANDS?.split(",")
.map((s) => s.trim())
.filter(Boolean) ?? [];
const excluded = new Set(process.env.INTERACTIVE_EXCLUDE?.split(",").map((s) => s.trim().toLowerCase()) ?? []);
return [...DEFAULT_INTERACTIVE_COMMANDS, ...additional].filter((cmd) => !excluded.has(cmd.toLowerCase()));
}
function isInteractiveCommand(command: string): boolean {
const trimmed = command.trim().toLowerCase();
const commands = getInteractiveCommands();
for (const cmd of commands) {
const cmdLower = cmd.toLowerCase();
// Match at start
if (trimmed === cmdLower || trimmed.startsWith(`${cmdLower} `) || trimmed.startsWith(`${cmdLower}\t`)) {
return true;
}
// Match after pipe: "cat file | less"
const pipeIdx = trimmed.lastIndexOf("|");
if (pipeIdx !== -1) {
const afterPipe = trimmed.slice(pipeIdx + 1).trim();
if (afterPipe === cmdLower || afterPipe.startsWith(`${cmdLower} `)) {
return true;
}
}
}
return false;
}
export default function (pi: ExtensionAPI) {
pi.on("user_bash", async (event, ctx) => {
let command = event.command;
let forceInteractive = false;
// Check for !i prefix (command comes without the leading !)
// The prefix parsing happens before this event, so we check if command starts with "i "
if (command.startsWith("i ") || command.startsWith("i\t")) {
forceInteractive = true;
command = command.slice(2).trim();
}
const shouldBeInteractive = forceInteractive || isInteractiveCommand(command);
if (!shouldBeInteractive) {
return; // Let normal handling proceed
}
// No UI available (print mode, RPC, etc.)
if (!ctx.hasUI) {
return {
result: { output: "(interactive commands require TUI)", exitCode: 1, cancelled: false, truncated: false },
};
}
// Use ctx.ui.custom() to get TUI access, then run the command
const exitCode = await ctx.ui.custom<number | null>((tui, _theme, _kb, done) => {
// Stop TUI to release terminal
tui.stop();
// Clear screen
process.stdout.write("\x1b[2J\x1b[H");
// Run command with full terminal access
const shell = process.env.SHELL || "/bin/sh";
const result = spawnSync(shell, ["-c", command], {
stdio: "inherit",
env: process.env,
});
// Restart TUI
tui.start();
tui.requestRender(true);
// Signal completion
done(result.status);
// Return empty component (immediately disposed since done() was called)
return { render: () => [], invalidate: () => {} };
});
// Return result to prevent default bash handling
const output =
exitCode === 0
? "(interactive command completed successfully)"
: `(interactive command exited with code ${exitCode})`;
return {
result: {
output,
exitCode: exitCode ?? 1,
cancelled: false,
truncated: false,
},
};
});
}