iterm2-node
v0.1.0
Published
Node.js client library for the iTerm2 API, inspired by github.com/tmc/it2.
Maintainers
Readme
iterm2-node
Node.js client library for the iTerm2 API.
This package is library-only. It does not ship a CLI.
Relationship To tmc/it2
This project is inspired by and informed by
github.com/tmc/it2, Travis Cline's Go project
for controlling iTerm2 sessions, splits, text I/O, buffers, tabs, and windows.
The overlap is intentional at the workflow/API-concept level: sessions, tabs, windows, splits, text input, buffer reads, variables, profiles, colors, and authentication are exposed with names that should feel familiar to users of the Go project.
This is not a line-for-line port of tmc/it2, and it is not an official Node
package from that project. The implementation is written in JavaScript for
Node.js and intentionally omits the Go project's CLI, plugin system, agent
state detection, broadcast helpers, and higher-level terminal workflow tools.
tmc/it2 is MIT licensed. The license for this package keeps the Travis Cline
copyright notice alongside the iterm2-node contributor notice.
Requirements
- Node.js 18+
- macOS with iTerm2 3.3.0+
- iTerm2 Python API enabled:
iTerm2 Settings > General > Magic > Enable Python API
Configure iTerm2
iterm2-node talks to the same local API server used by iTerm2's Python API. You
do not need to install Python packages, but iTerm2's API server must be enabled.
iTerm2 documents this in its Python API docs and its Python API security page,
which describes the local Unix domain socket and cookie-based authentication
model.
- Open iTerm2.
- Open
iTerm2 > Settings. - Go to
General > Magic. - Enable
Enable Python APIorEnable Python API server, depending on the iTerm2 version. - Keep iTerm2 running while your Node process connects.
On the first connection from an external app, iTerm2 may ask macOS for
Automation permission so that the calling terminal app can request an API
cookie. Allow that prompt. The client stores the returned ITERM2_COOKIE and
ITERM2_KEY in the current process environment and sends them as iTerm2 API
headers.
You can verify configuration from this repository with:
node -e "const { auth } = require('.'); auth.checkAutomationEnabled().then(() => auth.requestAuthentication()).then(() => console.log('iTerm2 API ready'))"For an installed package, use require('iterm2-node') instead of require('.').
You can also enable the API server programmatically:
node -e "require('iterm2-node').auth.enableAutomation()"If iTerm2 is already running and the socket is not created, quit and reopen iTerm2 after changing the setting.
By default this client connects to iTerm2's Unix socket at:
~/Library/Application Support/iTerm2/private/socketIf that socket is unavailable, it falls back to ws://localhost:1912.
Optional: install iTerm2 shell integration if you use prompt-related APIs such
as getPrompt() or listPrompts(). In iTerm2 3.5+, this can be enabled with
Settings > Profiles > General > Command > Load shell integration automatically
for supported shells. You can also use iTerm2 > Install Shell Integration.
Common setup failures:
iTerm2 API automation is not enabled: enable the Python API setting above.authentication required: allow the macOS Automation prompt, or pass validITERM2_COOKIEandITERM2_KEYvalues in the Node process environment.ECONNREFUSEDor socket errors: make sure iTerm2 is running, then reopen iTerm2 if you just enabled the API server.
Official iTerm2 references:
Install
npm install iterm2-nodeFor local development in this repository:
npm installQuick Start
const { createClient } = require('iterm2-node');
async function main() {
const client = createClient();
await client.connect();
try {
const sessions = await client.listSessions();
const session = sessions[0];
await client.sendText(session.sessionId, 'echo hello from node\n');
const screen = await client.getScreenText(session.sessionId);
console.log(screen);
} finally {
await client.close();
}
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});By default the client uses iTerm2's Unix socket at
~/Library/Application Support/iTerm2/private/socket and falls back to
ws://localhost:1912.
Public API
The package root intentionally exposes only the library entry points:
createClient(options)ITerm2Clientauthproto- error classes
Everything else is accessed through a client instance.
Client Methods
Connection and protocol:
connect(options)close()sendRequest(payload, options)invokeFunction(invocation, options)subscribeToNotification(type, options)unsubscribeFromNotification(type, options)readNotification(options)notifications(options)
Sessions:
listSessions(options)listSessionsRaw(options)sendText(sessionId, text, options)splitPane(sessionId, options)moveSession(sourceSessionId, destSessionId, options)closeSessions(sessionIds, options)activateSession(sessionId, options)restartSession(sessionId, options)setSessionName(sessionId, name, options)setSessionBadge(sessionId, badge, options)getSessionBadge(sessionId, options)clearSessionBadge(sessionId, options)getPrompt(sessionId, options)getPromptById(sessionId, uniquePromptId, options)listPrompts(sessionId, options)
Screen and buffer:
getScreenContents(sessionId, options)getScreenText(sessionId, options)getBuffer(sessionId, options)getBufferWithStyles(sessionId, options)getBufferText(sessionId, options)getContents(sessionId, firstLine, numLines, options)clearBuffer(sessionId, options)findText(sessionId, pattern, options)
Variables and properties:
getVariable(sessionId, name, options)setVariable(sessionId, name, value, options)getVariableWithScope(scope, id, name, options)getMultipleVariablesWithScope(scope, id, names, options)setVariableWithScope(scope, id, name, value, options)listVariablesWithScope(scope, id, options)deleteVariableWithScope(scope, id, name, options)getSessionProperty(sessionId, property, options)setSessionProperty(sessionId, property, value, options)getSessionProfileProperty(sessionId, key, options)setSessionProfileProperty(sessionId, key, value, options)
Tabs and windows:
createTab(options)closeTabs(tabIds, options)activateTab(tabId, options)reorderTabs(assignments, options)setTabTitle(tabId, title, options)getTabTitle(tabId, options)clearTabTitle(tabId, options)setTabLayout(tabId, rootNode, options)setTabColor(tabId, red, green, blue, options)getTabColor(tabId, options)clearTabColor(tabId, options)createWindow(profileName, options)closeWindows(windowIds, options)activateWindow(windowId, options)listWindows(options)setWindowTitle(windowId, title, options)getWindowTitle(windowId, options)clearWindowTitle(windowId, options)getWindowProperty(windowId, property, options)setWindowProperty(windowId, property, value, options)
Profiles, colors, preferences, and other iTerm2 features:
listProfiles(options)listProfilesDetailed(options)getProfile(profileName, options)getProfileProperty(profileName, key, options)setProfileProperty(profileName, key, value, options)setProfileProperties(profileName, properties, options)listColorPresets(options)getColorPreset(name, options)applyColorPreset(presetName, profileName, options)getPreference(key, options)setPreference(key, value, options)getPreferences(keys, options)setPreferences(preferences, options)saveArrangement(name, windowId, options)restoreArrangement(name, options)listArrangements(options)getBroadcastDomains(options)setBroadcastDomains(domains, options)listTmuxConnections(options)sendTmuxCommand(connectionId, command, options)
Input, selection, and focus:
injectData(sessionIds, data, options)getCursor(sessionId, options)setCursor(sessionId, x, y, options)setGridSize(sessionId, width, height, options)getSelection(sessionId, options)setSelectionRange(sessionId, startX, startY, endX, endY, mode, options)setSelection(sessionId, start, end, options)clearSelection(sessionId, options)copySelection(options)pasteFromClipboard(sessionId, options)getFocus(options)
ID resolution helpers:
resolveSessionId(sessionId, options)resolveTabId(tabId, options)resolveWindowId(windowId, options)
Authentication Helpers
Authentication operations are exported under auth:
auth.requestAuthentication(options)auth.checkAutomationEnabled()auth.enableAutomation()auth.disableAutomation()auth.hasAuthentication(env)auth.clearAuthentication(env)auth.defaultSocketPath()auth.socketExists(socketPath)
The client can request authentication automatically unless
autoRequestAuth: false is passed to createClient().
Raw Protobuf Access
The iTerm2 API protobuf schema is included at proto/api.proto. Protocol
utilities are exported as proto:
const { proto } = require('iterm2-node');
const bytes = proto.encodeClientMessage({
id: 1,
listSessionsRequest: {}
});Use sendRequest() for raw request payloads when the high-level client does not
cover an iTerm2 API call yet.
Tests
npm test
npm run test:unit
npm run test:e2enpm test runs the unit suite.
test:unit is limited to protocol/computational behavior such as protobuf
encoding, request matching, ID resolution, text expansion, text chunking, and
session tree flattening.
test:e2e runs live iTerm2 tests. It creates, renames, splits, moves,
reorders, and closes temporary iTerm2 windows/tabs/sessions. It does not send
shell input or explicitly activate iTerm2 windows.
Set ITERM2_NODE_E2E_KEEP=1 to leave the temporary session open for
debugging.
License
MIT. See LICENSE.
Credit to Travis Cline and the
tmc/it2 project for the original Go iTerm2
automation work that informed this package.
