Skip to content

Commit 7fa1ff7

Browse files
feat(agent-manager): add WezTerm terminal support (#128)
* feat(agent-manager): add WezTerm terminal support Discover, focus, and type into the WezTerm pane that hosts a running agent, alongside the existing tmux / iTerm2 / Terminal.app flows. - TerminalFocusManager: add WEZTERM type; discover the owning pane from `wezterm cli list --format json` by matching the agent TTY against the JSON entry's `tty_name` field; focus via `wezterm cli activate-pane --pane-id`. Tried after tmux and before the macOS-only AppleScript probes, so non-macOS hosts short-circuit. - TtyWriter: send via two explicit `wezterm cli send-text --pane-id` calls 150ms apart — (1) the message as a positional argv element, then (2) Enter as a single carriage return byte (0x0d) with --no-paste. Both are discrete argv elements via execFile (no shell), so bytes are delivered verbatim regardless of shell metacharacters (injection-safe). The equivalent shell command for Enter is: wezterm cli send-text --pane-id <id> --no-paste $'\x0d' (ANSI-C dollar-single-quoted CR; execFile passes the actual CR byte). - TerminalFocusManager accepts an optional debug logger; `agent open --debug` wires it to the ai-devkit:terminal logger so users can inspect the matching/focus decision path. - Control is CLI-only (no AppleScript), so it works cross-platform. Missing/failed wezterm degrades like the tmux probe (null/false). No other CLI changes: agent send and channel bridges pick up WezTerm through the existing abstract findTerminal/focusTerminal/TtyWriter.send API. Spawning agents into WezTerm remains out of scope (TmuxManager). Validation: agent-manager + cli tsc/eslint clean; vitest 444 (agent-manager) and 843 (cli) / monorepo pass; WezTerm send/focus/debug branches covered incl. argv-injection-safety and CR-byte (0x0d) assertions. * fix(agent-manager): avoid exposing WezTerm prompts in argv
1 parent 61a6633 commit 7fa1ff7

12 files changed

Lines changed: 916 additions & 15 deletions

File tree

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
---
2+
phase: design
3+
title: System Design & Architecture
4+
description: Define the technical architecture, components, and data models
5+
---
6+
7+
# System Design & Architecture
8+
9+
## Architecture Overview
10+
**What is the high-level system structure?**
11+
12+
Terminal control is isolated in `packages/agent-manager/src/terminal/`. The CLI
13+
(`agent open`, `agent send`, channel bridges) only depends on three abstractions:
14+
`TerminalFocusManager.findTerminal/focusTerminal` and `TtyWriter.send`. Adding a
15+
new emulator means extending these three — no CLI change is required.
16+
17+
```mermaid
18+
graph TD
19+
CLI["ai-devkit CLI<br/>agent open / send / channel"] -->|pid| TFM["TerminalFocusManager.findTerminal"]
20+
TFM -->|tty| TMUX["tmux (innermost)"]
21+
TFM -->|tty| WEZ["wezterm cli list --format json (NEW)"]
22+
TFM -->|tty| ITERM["iTerm2 (AppleScript)"]
23+
TFM -->|tty| TERMAPP["Terminal.app (AppleScript)"]
24+
TFM -->|TerminalLocation| Focus["focusTerminal"]
25+
Focus --> WEZF["wezterm cli focus-pane --pane-id (NEW)"]
26+
CLI -->|location+msg| TW["TtyWriter.send"]
27+
TW --> WEZS["wezterm cli send-text --pane-id (NEW)"]
28+
```
29+
30+
- Key components
31+
- `TerminalType` enum — gains a `WEZTERM` member.
32+
- `TerminalFocusManager` — gains WezTerm discovery + focus.
33+
- `TtyWriter` — gains a WezTerm send branch.
34+
- WezTerm is controlled entirely through its `wezterm` CLI (no AppleScript), so
35+
the same code works on macOS, Linux, and Windows.
36+
37+
## Data Models
38+
**What data do we need to manage?**
39+
40+
- `TerminalType` enum: add `WEZTERM = 'wezterm'`.
41+
- `TerminalLocation` (unchanged shape):
42+
- `type: TerminalType.WEZTERM`
43+
- `identifier: string(paneId)` — WezTerm's global pane id (e.g. `"7"`), used
44+
by `activate-pane --pane-id` and `send-text --pane-id`.
45+
- `tty: string` — `/dev/...` device, for parity with other emulators.
46+
47+
## API Design
48+
**How do components communicate?**
49+
50+
Discovery and control happen via `execFile('wezterm', [...])` (promisified). No
51+
shell is used, so there is no string interpolation. Prompt text is written to
52+
`send-text` over stdin instead of argv, keeping message contents out of local
53+
process listings while preserving shell-injection safety.
54+
55+
- Discover pane: `wezterm cli list --format json`
56+
- Parse JSON array; find entry whose **`tty_name`** equals the target
57+
`/dev/...` (the JSON field is `tty_name`, not `tty`).
58+
- Return `{ type: WEZTERM, identifier: String(pane_id), tty }`.
59+
- Focus pane: `wezterm cli activate-pane --pane-id <id>` → success on zero exit.
60+
- Send text: two explicit `wezterm cli send-text --pane-id <id>` calls.
61+
- Step 1 (text): `send-text --pane-id <id>` with the message body written to
62+
stdin.
63+
- Step 2 (Enter): a single carriage return byte (0x0d) as an argv element
64+
with `--no-paste`. The equivalent shell command is
65+
`wezterm cli send-text --pane-id <id> --no-paste $'\x0d'` (note the
66+
dollar-single-quoted `$'\x0d'`), so the CR is delivered literally rather
67+
than wrapped in paste brackets.
68+
- 150 ms pacing between the two, mirroring the tmux/iTerm/Terminal
69+
convention so a bracketed-paste-aware TUI still sees Enter as a submit.
70+
71+
## Component Breakdown
72+
**What are the major building blocks?**
73+
74+
- `src/terminal/TerminalFocusManager.ts`
75+
- `findTerminal`: insert WezTerm check **after tmux, before iTerm2**.
76+
(tmux-inside-wezterm still resolves to tmux; cross-platform WezTerm is tried
77+
before macOS-only AppleScript probes.)
78+
- `findWeztermPane(tty)`: call `wezterm cli list --format json`, JSON-parse,
79+
match `tty_name`, return location or `null`. Swallow ENOENT/parse/non-zero.
80+
- `focusWeztermPane(paneId)`: `wezterm cli activate-pane --pane-id <id>`.
81+
- Optional `debug` logger (constructor): emits one line per discovery/focus
82+
step (pid/tty, each probe's match/no-match, focus result) so the
83+
`agent open --debug` command can show the decision path.
84+
- `src/terminal/TtyWriter.ts`
85+
- `send`: add `WEZTERM` case → `sendViaWezterm(identifier, message)`.
86+
- `sendViaWezterm`: text via stdin, then a CR byte (0x0d) with `--no-paste`
87+
— 150 ms apart; throws a descriptive error on failure.
88+
- `src/terminal/index.ts`: no change (`TerminalType` already re-exported).
89+
- CLI: no change — it consumes the abstract API only.
90+
91+
## Design Decisions
92+
**Why did we choose this approach?**
93+
94+
- **CLI-over-AppleScript.** WezTerm is cross-platform and ships a stable CLI.
95+
Reusing it avoids macOS-only scripting and matches how tmux is handled.
96+
- **Discovery by TTY from `cli list --format json`.** JSON is stable to parse;
97+
TTY matching reuses the exact identity model of the other emulators.
98+
- **Two-step text + Enter.** Keeps identical semantics to the three existing
99+
senders (documented to survive bracketed-paste TUIs) and avoids special-casing.
100+
- **Graceful degradation.** `wezterm` missing/failed is caught exactly like the
101+
tmux probe, so behavior for non-WezTerm users is unchanged.
102+
- Alternatives considered
103+
- Parsing the human-readable `cli list` table — fragile across versions;
104+
rejected in favor of `--format json`.
105+
- WezTerm GUI app process-name sniffing — differs by platform
106+
(`wezterm-gui` vs bundled `wezterm`); rejected; we let `cli list` be the
107+
source of truth and catch failure.
108+
- Single-step send (text + newline together) — rejected for consistency with
109+
the documented two-step convention used everywhere else.
110+
111+
## Non-Functional Requirements
112+
**How should the system perform?**
113+
114+
- Performance: one extra short-lived subprocess probe on `findTerminal` only when
115+
earlier probes miss; same O(processes) cost profile as today.
116+
- Security: no shell invocation; the message is written through stdin so it is
117+
not exposed through process arguments, shell metacharacters remain data, and
118+
Enter is a fixed CR byte.
119+
- Reliability: every WezTerm path is wrapped so a missing binary, a failed JSON
120+
parse, or a non-running instance returns `null`/`false`/throws-with-context
121+
instead of crashing the CLI.
122+
- Compat: existing emulator tests run unmodified.
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
---
2+
phase: implementation
3+
title: Implementation Guide
4+
description: Technical implementation notes, patterns, and code guidelines
5+
---
6+
7+
# Implementation Guide — WezTerm support
8+
9+
## Development Setup
10+
**How do we get started?**
11+
12+
- Work in worktree `feature-wezterm-support`; `npm ci` at the repo root.
13+
- Run agent-manager tests: `npx vitest run` in `packages/agent-manager`.
14+
- WezTerm is **not** required to develop/CI this: all control paths go through
15+
`execFile` and are covered by mocked unit tests.
16+
17+
## Code Structure
18+
**How is the code organized?**
19+
20+
- `packages/agent-manager/src/terminal/`
21+
- `TerminalFocusManager.ts` — discovery + focus (one method pair per emulator).
22+
- `TtyWriter.ts` — input dispatch (one sender per emulator).
23+
- `index.ts` — re-exports (`TerminalType` already exported; no change needed).
24+
- No CLI changes: `agent open`, `agent send`, and channel bridges consume the
25+
abstract `findTerminal` / `focusTerminal` / `TtyWriter.send` API only.
26+
27+
## Implementation Notes
28+
**Key technical details to remember:**
29+
30+
### Discovery (`TerminalFocusManager.findWeztermPane`)
31+
- `execFile('wezterm', ['cli', 'list', '--format', 'json'])`.
32+
- Parse JSON; match the entry whose **`tty_name`** equals `/dev/<agent-tty>`;
33+
use `pane_id` as `identifier`. Only `tty_name` and `pane_id` are read; extra
34+
fields are
35+
ignored for forward-compat.
36+
- `try/catch` swallows ENOENT (binary missing), non-running mux, and malformed
37+
JSON → returns `null`, identical to the tmux probe's failure handling.
38+
- Probe order in `findTerminal`: tmux → **WezTerm** → iTerm2 → Terminal.app.
39+
tmux wins when nested inside WezTerm; WezTerm is tried before the macOS-only
40+
AppleScript probes so non-macOS hosts short-circuit cleanly.
41+
42+
### Focus (`TerminalFocusManager.focusWeztermPane`)
43+
- `execFile('wezterm', ['cli', 'activate-pane', '--pane-id', identifier])`.
44+
- Returns `true` on zero exit, `false` (no throw) on any error.
45+
46+
### Send (`TtyWriter.sendViaWezterm`)
47+
- Two explicit `wezterm cli send-text --pane-id <id>` calls, 150 ms apart:
48+
- Step 1 (text): `['cli', 'send-text', '--pane-id', paneId]` with the message
49+
body written to stdin, keeping prompt contents out of local process
50+
listings.
51+
- Step 2 (Enter): `['cli', 'send-text', '--pane-id', paneId, '--no-paste',
52+
'\x0d']`, where the argv element `'\x0d'` is the JS string holding the
53+
single carriage-return byte (0x0d). The equivalent shell command is
54+
`wezterm cli send-text --pane-id <id> --no-paste $'\x0d'` (note the
55+
dollar-single-quoted `$'\x0d'`), and `--no-paste` delivers the CR
56+
literally rather than wrapped in paste brackets.
57+
- Same two-step text+Enter convention as tmux/iTerm2/Terminal.app so a
58+
bracketed-paste-aware TUI still sees Enter as a submit.
59+
60+
### Patterns & Best Practices
61+
- Shell injection safety without a shell: all wezterm control is via
62+
`execFile('wezterm', [...argv])`, which spawns the process directly. The
63+
message is written through stdin, so shell metacharacters are delivered as
64+
data without exposing prompt text through argv.
65+
- No AppleScript: WezTerm is cross-platform; the CLI is the single integration.
66+
67+
### Debug trace (`agent open --debug`)
68+
- `TerminalFocusManager` takes an optional `debug?: (message: string) => void`
69+
callback in its constructor. When set, `findTerminal`/`focusTerminal` emit one
70+
human-readable line per step (pid/tty, each emulator probe's match/no-match,
71+
focus result).
72+
- The `agent open --debug` command wires this to the existing
73+
`ai-devkit:terminal` debug logger (`createLogger('terminal')` + `enableDebug()`),
74+
reusing the repo's `--debug` convention used by `agent start`/`channel`.
75+
76+
## Integration Points
77+
**How do pieces connect?**
78+
79+
- Public surface added: `TerminalType.WEZTERM = 'wezterm'` (new enum member) and
80+
the existing `TerminalLocation` shape (identifier = pane id).
81+
- Consumers (`packages/cli` `agent.ts`, `agent.service.ts`, `channel-runner.ts`)
82+
are unchanged; they pick up WezTerm automatically through the abstract API.
83+
84+
## Error Handling
85+
**How do we handle failures?**
86+
87+
- Discovery: missing/failed WezTerm → `null` → UNKNOWN fallback → CLI reports it
88+
cannot focus, exactly like any other unrecognized emulator.
89+
- Focus: errors → `false` (graceful).
90+
- Send: errors → thrown with context (consistent with the other senders).
91+
92+
## Performance Considerations
93+
**How do we keep it fast?**
94+
95+
- One extra short-lived `wezterm cli list` subprocess only when tmux didn't
96+
match. `findTerminal` is called once per `agent open`/`send`.
97+
98+
## Security Notes
99+
**What security measures are in place?**
100+
101+
- No shell; `paneId` originates from WezTerm's own JSON (numeric) and the
102+
message is written to `send-text` through stdin, so prompt text is not exposed
103+
through process arguments and shell metacharacters remain data.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
phase: planning
3+
title: Project Planning & Task Breakdown
4+
description: Break down work into actionable tasks and estimate timeline
5+
---
6+
7+
# Project Planning & Task Breakdown
8+
9+
## Milestones
10+
**What are the major checkpoints?**
11+
12+
- [ ] M1: WezTerm discovery returns a `WEZTERM` location (unit-tested).
13+
- [ ] M2: Focus + send work end-to-end against the WezTerm CLI (unit-tested).
14+
- [ ] M3: Full package test suite green; docs updated; PR opened.
15+
16+
## Task Breakdown
17+
**What specific work needs to be done?**
18+
19+
### Phase 1: Discovery
20+
- [x] T1.1: Add `WEZTERM = 'wezterm'` to `TerminalType`.
21+
- [x] T1.2: Add `findWeztermPane(tty)` calling `wezterm cli list --format json`,
22+
matching `tty` → `pane_id`; swallow ENOENT/parse/non-zero.
23+
- [x] T1.3: Insert WezTerm probe in `findTerminal` after tmux, before iTerm2.
24+
25+
### Phase 2: Control
26+
- [x] T2.1: Add `focusWeztermPane(paneId)` (`wezterm cli focus-pane --pane-id`)
27+
and a `WEZTERM` case in `focusTerminal`.
28+
- [x] T2.2: Add `sendViaWezterm(identifier, message)` (two-step text + Enter via
29+
stdin) and a `WEZTERM` case in `TtyWriter.send`.
30+
31+
### Phase 3: Tests & Docs
32+
- [x] T3.1: Unit tests in `TerminalFocusManager.test.ts` (found / not-installed
33+
/ no-match / malformed-json / precedence / no-osascript / focus ok / focus
34+
fail).
35+
- [x] T3.2: Unit tests in `TtyWriter.test.ts` (two-step send / pane-id / failure
36+
/ still-unsupported).
37+
- [x] T3.3: Update `packages/agent-manager/README.md` terminal support list.
38+
- [ ] T3.4: Run `npm test` (done); simplify-implementation review (done, no changes); commit; open PR.
39+
40+
## Dependencies
41+
**What needs to happen in what order?**
42+
43+
- T1.1 → T1.2 → T1.3 (enum before its consumers).
44+
- T2.* depend on T1.1.
45+
- T3.1/T3.2 written before/with their targets (TDD).
46+
47+
## Timeline & Estimates
48+
**When will things be done?**
49+
50+
- Single small, well-scoped change; all phases in one session.
51+
52+
## Risks & Mitigation
53+
**What could go wrong?**
54+
55+
- WezTerm JSON schema drift across versions → mitigate by reading only `tty` and
56+
`pane_id` defensively and falling back to `null` on any anomaly.
57+
- Cannot run real WezTerm in CI → rely on execFile-mocked unit tests; document
58+
manual verification.
59+
60+
## Resources Needed
61+
**What do we need to succeed?**
62+
63+
- Existing vitest + execFile mock harness in `__tests__/terminal/`.
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
---
2+
phase: requirements
3+
title: Requirements & Problem Understanding
4+
description: Clarify the problem space, gather requirements, and define success criteria
5+
---
6+
7+
# Requirements & Problem Understanding
8+
9+
## Problem Statement
10+
**What problem are we solving?**
11+
12+
- `@ai-devkit/agent-manager` can discover and focus terminal sessions for an
13+
already-running agent in **tmux**, **iTerm2**, and macOS **Terminal.app** via
14+
`TerminalFocusManager` / `TtyWriter`.
15+
- Users who run coding agents inside **WezTerm** get no terminal resolution: the
16+
agent is detected (PID/TTY are known) but `findTerminal` falls through to
17+
`UNKNOWN`, so `agent open`, `agent send`, and channel bridges cannot focus or
18+
type into the WezTerm pane that owns the agent.
19+
- Current workaround: none from the CLI; users must switch panes manually.
20+
21+
## Goals & Objectives
22+
**What do we want to achieve?**
23+
24+
- Primary goals
25+
- Discover the WezTerm pane that owns a running agent by matching the agent
26+
PID's TTY against WezTerm's panes.
27+
- Focus that pane (`agent open`) and send keyboard input to it (`agent send`,
28+
channel bridge) through WezTerm's CLI.
29+
- Keep all existing tmux / iTerm2 / Terminal.app behavior byte-for-byte
30+
unchanged.
31+
- Secondary goals
32+
- Cross-platform (WezTerm runs on macOS, Linux, Windows) without AppleScript.
33+
- Graceful no-op when WezTerm is not installed or not running.
34+
- Non-goals (what's explicitly out of scope)
35+
- Spawning new agents into WezTerm (that is `TmuxManager`'s session-create
36+
responsibility; WezTerm spawn is not added here).
37+
- Splitting/tiling panes, theming, or WezTerm config generation.
38+
- Detecting the WezTerm emulator version or multiplexing across multiple
39+
WezTerm mux servers beyond the default local instance.
40+
41+
## User Stories & Use Cases
42+
**How will users interact with the solution?**
43+
44+
- As a developer running Claude Code/Codex/Gemini inside a WezTerm pane, I run
45+
`ai-devkit agent open <name>` so the WezTerm pane hosting the agent is
46+
focused/raised.
47+
- As an orchestrator, I run `ai-devkit agent send "<msg>" --id <name>` so the
48+
text is typed into the correct WezTerm pane and submitted.
49+
- As a channel (Telegram) bridge user, incoming messages are forwarded to the
50+
WezTerm pane owning the agent.
51+
- Edge cases
52+
- WezTerm binary not installed → behaves as before (UNKNOWN fallback).
53+
- WezTerm installed but no instance running → behaves as before.
54+
- Agent runs inside **tmux inside WezTerm** → resolves to tmux (innermost
55+
first), unchanged.
56+
57+
## Success Criteria
58+
**How will we know when we're done?**
59+
60+
- `TerminalFocusManager.findTerminal(pid)` returns a `WEZTERM` location when the
61+
TTY belongs to a WezTerm pane, and only when the WezTerm CLI is available.
62+
- `focusTerminal(weztermLocation)` focuses the matching pane; returns `false` on
63+
any failure without throwing.
64+
- `TtyWriter.send(weztermLocation, msg)` types the message and submits it.
65+
- Existing tmux/iTerm2/Terminal.app tests pass unchanged.
66+
- New unit tests cover discovery (found / not-installed / tty-mismatch) and send
67+
(text+Enter, failure). `npm test` for `@ai-devkit/agent-manager` is green.
68+
69+
## Constraints & Assumptions
70+
**What limitations do we need to work within?**
71+
72+
- WezTerm is controlled exclusively through its `wezterm` CLI; no scripting host
73+
is assumed (so no AppleScript on non-macOS).
74+
- We rely on the documented, stable WezTerm CLI surface: `wezterm cli list
75+
--format json`, `wezterm cli focus-pane --pane-id <id>`, `wezterm cli
76+
send-text --pane-id <id>` (stdin).
77+
- TTY matching requires the agent process to report a TTY (same prerequisite as
78+
the existing emulators).
79+
- Assumption: a single default local WezTerm mux server (the common case).
80+
81+
## Questions & Open Items
82+
**What do we still need to clarify?**
83+
84+
- None blocking. Spawn-into-WezTerm and multi-server muxing are deferred as
85+
explicit non-goals above.

0 commit comments

Comments
 (0)