Skip to content

Commit e506a6e

Browse files
committed
docs: comprehensively update project documentation
- Update AGENTS.md with complete sections including code style conventions, error handling patterns, security best practices, dependency management, release process, contributing guidelines, and troubleshooting - Update README.md with accurate repository URL, complete tool descriptions, correct REST API endpoints, proper WebSocket message examples, and accurate development instructions - Correct inaccuracies and add missing information based on thorough codebase analysis - Improve documentation quality and completeness for developers and users
1 parent d6de54e commit e506a6e

2 files changed

Lines changed: 297 additions & 24 deletions

File tree

AGENTS.md

Lines changed: 265 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,80 @@ This document is the authoritative and up-to-date guide for both agentic coding
7979
- Run single/filtered unit test: `bun test --match "<pattern>"`
8080
- **Other:**
8181
- `bun run clean` — Remove build artifacts, test results, etc.
82+
- `bun run ci` — Run quality checks and all tests (used by CI pipeline)
8283

8384
**Note:** Many scripts have special requirements or additional ENV flags; see inline package.json script comments for platform- or environment-specific details (e.g. Playwright+Bun TS support requires `PW_DISABLE_TS_ESM=1`).
8485

8586
---
8687

88+
## Code Style & Conventions
89+
90+
### Naming Conventions
91+
92+
- **Functions/Variables**: camelCase (`setOnSessionUpdate`, `rawOutputCallbacks`)
93+
- **Types/Classes**: PascalCase (`PTYManager`, `SessionLifecycleManager`)
94+
- **Constants**: UPPER_CASE (`DEFAULT_READ_LIMIT`, `MAX_LINE_LENGTH`)
95+
- **Directories**: kebab-case (`src/web/client`, `e2e`)
96+
- **Files**: kebab-case for directories, camelCase for components/hooks (`useWebSocket.ts`, `TerminalRenderer.tsx`)
97+
98+
### TypeScript Configuration
99+
100+
- Strict TypeScript settings enabled (`strict: true`)
101+
- Module resolution: `"bundler"` with `"moduleResolution": "bundler"`
102+
- Target: ESNext with modern features
103+
- No implicit returns or unused variables/parameters allowed
104+
- Explicit type annotations required where beneficial
105+
106+
### Formatting (Prettier)
107+
108+
- **Semicolons**: Disabled (`semi: false`)
109+
- **Quotes**: Single quotes preferred (`singleQuote: true`)
110+
- **Trailing commas**: ES5 style (`trailingComma: "es5"`)
111+
- **Print width**: 100 characters (`printWidth: 100`)
112+
- **Indentation**: 2 spaces, no tabs (`tabWidth: 2`, `useTabs: false`)
113+
114+
### Import/Export Style
115+
116+
- Use ES6 imports/exports
117+
- Group imports: external libraries first, then internal modules
118+
- Prefer named exports over default exports for better tree-shaking
119+
- Use absolute imports for internal modules where possible
120+
121+
### Documentation
122+
123+
- Use JSDoc comments for public APIs
124+
- Inline comments for complex logic
125+
- No redundant comments on self-explanatory code
126+
127+
---
128+
129+
## Error Handling & Logging
130+
131+
### Error Handling Patterns
132+
133+
- Use try/catch blocks for operations that may fail
134+
- Throw descriptive `Error` objects with clear messages
135+
- Handle errors gracefully in async operations
136+
- Validate inputs and provide meaningful error messages
137+
- Use custom error builders for common error types (e.g., `buildSessionNotFoundError`)
138+
139+
### Logging Approach
140+
141+
- Logging is handled through the OpenCode client's notification system
142+
- Use `client.session.promptAsync()` for user-facing notifications
143+
- Session lifecycle events (start, exit) generate notifications automatically
144+
- No dedicated logging files; logging is integrated with OpenCode's session system
145+
- Debug logging can be enabled via OpenCode's `--log-level DEBUG` flag
146+
147+
### Exception Safety
148+
149+
- Operations that modify state should be atomic where possible
150+
- Clean up resources in error paths (session cleanup, buffer management)
151+
- Silent failure in notification paths to prevent cascading errors
152+
- Validate session state before operations
153+
154+
---
155+
87156
## Testing Approach
88157

89158
- **Unit Tests:**
@@ -125,4 +194,199 @@ This document is the authoritative and up-to-date guide for both agentic coding
125194
126195
---
127196
128-
## [Next sections will follow this improved outline.]
197+
## Security Best Practices
198+
199+
### Input Validation
200+
201+
- Validate all user inputs before processing
202+
- Use regex pattern validation for search/filter operations
203+
- Sanitize file paths and command arguments
204+
- Check permissions before executing operations
205+
206+
### Process Security
207+
208+
- PTY sessions run with user permissions only
209+
- External directory access controlled via permission settings
210+
- No elevated privileges or sudo operations
211+
- Session isolation prevents cross-session interference
212+
213+
### Dependency Security
214+
215+
- Regular dependency updates via `bun install`
216+
- CI includes security scanning (CodeQL, dependency review)
217+
- No secrets or credentials committed to repository
218+
- Environment variables used for sensitive configuration
219+
220+
### Code Security
221+
222+
- Strict TypeScript prevents type-related vulnerabilities
223+
- ESLint rules enforce secure coding patterns
224+
- No dynamic code execution or eval usage
225+
- Buffer overflow protection through TypeScript bounds checking
226+
227+
---
228+
229+
## Dependency Management
230+
231+
### Package Management
232+
233+
- **Runtime**: Bun for fast package management and execution
234+
- **Dependencies**: Listed in `package.json` with specific versions
235+
- **Lockfile**: `bun.lockb` ensures reproducible installs
236+
- **Peer Dependencies**: TypeScript ^5 required
237+
238+
### Key Dependencies
239+
240+
- `@opencode-ai/plugin` & `@opencode-ai/sdk` — OpenCode integration
241+
- `@xterm/xterm` & `@xterm/addon-*` — Terminal emulation
242+
- `bun-pty` — PTY process management
243+
- `react` & `react-dom` — Web UI framework
244+
- `strip-ansi` — ANSI escape sequence removal
245+
246+
### Development Dependencies
247+
248+
- Testing: `@playwright/test`, Bun test runner
249+
- Code Quality: `eslint`, `prettier`, `typescript`
250+
- Build: `vite`, `@vitejs/plugin-react`
251+
252+
### Updating Dependencies
253+
254+
- Use `bun update <package>` for specific package updates
255+
- Run full test suite after updates
256+
- Check for breaking changes in changelogs
257+
- Update lockfile and commit together
258+
259+
---
260+
261+
## Release Process
262+
263+
### Automated Release
264+
265+
- Releases triggered by version bumps to main branch
266+
- Use `./release.sh` script for version management:
267+
```sh
268+
./release.sh --patch # Patch version bump
269+
./release.sh --minor # Minor version bump
270+
./release.sh --major # Major version bump
271+
./release.sh --dry-run # Preview changes
272+
```
273+
274+
### Release Workflow
275+
276+
1. **Version Bump**: Script updates `package.json` version
277+
2. **Git Tag**: Creates `v{X.Y.Z}` tag on main branch
278+
3. **GitHub Actions**: Triggers release workflow
279+
4. **NPM Publish**: Automated publishing with provenance
280+
5. **Changelog**: Generated from git commit history
281+
282+
### Pre-release Checks
283+
284+
- All tests pass (`bun run ci`)
285+
- Build succeeds (`bun run build`)
286+
- No uncommitted changes
287+
- Git working directory clean
288+
289+
### Post-release
290+
291+
- Version available on NPM within minutes
292+
- OpenCode plugin updates automatically
293+
- GitHub release created with changelog
294+
295+
---
296+
297+
## Contributing Guidelines
298+
299+
### Development Workflow
300+
301+
1. **Fork & Branch**: Create feature branch from main
302+
2. **Code Changes**: Follow established conventions
303+
3. **Testing**: Add/update tests for new functionality
304+
4. **Quality Checks**: Run `bun run quality` before committing
305+
5. **Commit**: Use descriptive commit messages
306+
6. **Pull Request**: Create PR with clear description
307+
308+
### Pull Request Requirements
309+
310+
- **Tests**: Include unit and E2E tests as appropriate
311+
- **Documentation**: Update AGENTS.md for significant changes
312+
- **Breaking Changes**: Clearly document API changes
313+
- **Code Review**: Address review feedback
314+
- **CI**: All checks must pass
315+
316+
### Code Review Checklist
317+
318+
- [ ] TypeScript types correct and complete
319+
- [ ] Error handling appropriate
320+
- [ ] Tests added/updated
321+
- [ ] Documentation updated
322+
- [ ] Security considerations addressed
323+
- [ ] Performance implications considered
324+
- [ ] Code style conventions followed
325+
326+
### Commit Message Convention
327+
328+
- Use imperative mood: "Add feature" not "Added feature"
329+
- Start with action verb (Add, Fix, Update, Remove, etc.)
330+
- Keep first line under 50 characters
331+
- Add detailed description for complex changes
332+
333+
---
334+
335+
## Troubleshooting
336+
337+
### Common Issues
338+
339+
#### Build Failures
340+
341+
- **Type errors**: Run `bun run typecheck` to identify issues
342+
- **Lint errors**: Use `bun run lint:fix` for auto-fixable issues
343+
- **Missing dependencies**: Run `bun install` to ensure all packages installed
344+
345+
#### Test Failures
346+
347+
- **Unit tests**: Check for race conditions or state leakage between tests
348+
- **E2E tests**: Verify dev server running, check browser console for errors
349+
- **Flaky tests**: Increase timeouts or add explicit waits
350+
351+
#### Runtime Issues
352+
353+
- **Permission denied**: Check PTY session permissions in OpenCode settings
354+
- **Session not found**: Verify session ID and lifecycle
355+
- **Buffer issues**: Check buffer size limits and regex patterns
356+
357+
#### Development Environment
358+
359+
- **Bun version**: Ensure Bun latest version installed
360+
- **Node modules**: Clear cache with `rm -rf node_modules && bun install`
361+
- **Port conflicts**: Check if dev server ports (8766) are available
362+
363+
### Debug Mode
364+
365+
- Enable verbose logging: `opencode --log-level DEBUG --print-logs`
366+
- Check debug logs in `~/.local/share/opencode/logs/`
367+
- Use browser dev tools for web UI debugging
368+
369+
### Getting Help
370+
371+
- Check existing issues on GitHub
372+
- Review README.md and this AGENTS.md
373+
- Create detailed bug reports with reproduction steps
374+
- Include environment info (Bun version, OS, OpenCode version)
375+
376+
---
377+
378+
## Appendix: Minimal .opencode/package.json
379+
380+
For local plugin development, create a minimal `package.json` in `.opencode/`:
381+
382+
```json
383+
{
384+
"name": "opencode-local-plugins",
385+
"private": true,
386+
"dependencies": {
387+
"your-plugin-dep": "^1.0.0"
388+
}
389+
}
390+
```
391+
392+
Then run `bun install` in `.opencode/` and restart OpenCode.

README.md

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ This plugin gives the agent full control over multiple terminal sessions, like t
2424
- **Permission Support**: Respects OpenCode's bash permission settings
2525
- **Session Lifecycle**: Sessions persist until explicitly killed
2626
- **Auto-cleanup**: PTYs are cleaned up when OpenCode sessions end
27+
- **Web UI**: Modern React-based interface for session management
28+
- **Real-time Streaming**: WebSocket-based live output updates
2729

2830
## Setup
2931

@@ -52,13 +54,14 @@ opencode
5254

5355
## Tools Provided
5456

55-
| Tool | Description |
56-
| ----------- | --------------------------------------------------------------------------- |
57-
| `pty_spawn` | Create a new PTY session (command, args, workdir, env, title, notifyOnExit) |
58-
| `pty_write` | Send input to a PTY (text, escape sequences like `\x03` for Ctrl+C) |
59-
| `pty_read` | Read output buffer with pagination and optional regex filtering |
60-
| `pty_list` | List all PTY sessions with status, PID, line count |
61-
| `pty_kill` | Terminate a PTY, optionally cleanup the buffer |
57+
| Tool | Description |
58+
| ---------------- | --------------------------------------------------------------------------- |
59+
| `pty_spawn` | Create a new PTY session (command, args, workdir, env, title, notifyOnExit) |
60+
| `pty_write` | Send input to a PTY (text, escape sequences like `\x03` for Ctrl+C) |
61+
| `pty_read` | Read output buffer with pagination and optional regex filtering |
62+
| `pty_list` | List all PTY sessions with status, PID, line count |
63+
| `pty_kill` | Terminate a PTY, optionally cleanup the buffer |
64+
| `pty_server_url` | Get the URL of the running PTY web server instance |
6265

6366
## Web UI
6467

@@ -90,14 +93,17 @@ This will:
9093

9194
The web server provides a REST API for session management:
9295

93-
| Method | Endpoint | Description |
94-
| -------- | -------------------------- | -------------------------------- |
95-
| `GET` | `/api/sessions` | List all PTY sessions |
96-
| `POST` | `/api/sessions` | Create a new PTY session |
97-
| `GET` | `/api/sessions/:id` | Get session details |
98-
| `GET` | `/api/sessions/:id/output` | Get session output buffer |
99-
| `DELETE` | `/api/sessions/:id` | Kill and cleanup a session |
100-
| `GET` | `/health` | Server health check with metrics |
96+
| Method | Endpoint | Description |
97+
| ------ | -------------------------------- | -------------------------------------- |
98+
| `GET` | `/api/sessions` | List all PTY sessions |
99+
| `POST` | `/api/sessions` | Create a new PTY session |
100+
| `GET` | `/api/sessions/:id` | Get session details |
101+
| `POST` | `/api/sessions/:id/input` | Send input to a session |
102+
| `POST` | `/api/sessions/:id/kill` | Kill and cleanup a session |
103+
| `GET` | `/api/sessions/:id/buffer/plain` | Get session output buffer (plain text) |
104+
| `GET` | `/api/sessions/:id/buffer/raw` | Get session output buffer (raw) |
105+
| `POST` | `/api/sessions/clear` | Clear all sessions |
106+
| `GET` | `/health` | Server health check with metrics |
101107

102108
#### Session Creation
103109

@@ -120,8 +126,10 @@ const ws = new WebSocket('ws://localhost:8766/ws')
120126

121127
ws.onmessage = (event) => {
122128
const data = JSON.parse(event.data)
123-
if (data.type === 'data') {
124-
console.log('New output:', data.data)
129+
if (data.type === 'raw_data') {
130+
console.log('New output:', data.rawData)
131+
} else if (data.type === 'session_list') {
132+
console.log('Session list:', data.sessions)
125133
}
126134
}
127135
```
@@ -131,14 +139,14 @@ ws.onmessage = (event) => {
131139
For development with hot reloading:
132140

133141
```bash
134-
# Terminal 1: Start the backend server
135-
bun run dev:backend
136-
137-
# Terminal 2: Start the React dev server
142+
# Terminal 1: Start the React dev server
138143
bun run dev
144+
145+
# Terminal 2: Start the PTY server (in another terminal)
146+
bun run e2e/test-web-server.ts
139147
```
140148

141-
The React app will be available at `http://localhost:5173` with hot reloading.
149+
The React app will be available at `http://localhost:5173` with hot reloading, and the PTY server at `http://localhost:8766`.
142150

143151
## Usage Examples
144152

@@ -257,6 +265,7 @@ This plugin respects OpenCode's [permission settings](https://opencode.ai/docs/p
257265
5. **Write**: Agent can send any input including escape sequences
258266
6. **Lifecycle**: Sessions track status (running/exited/killed), persist until cleanup
259267
7. **Notify**: When `notifyOnExit` is true, sends a message to the session when the process exits
268+
8. **Web UI**: React frontend connects via WebSocket for real-time updates
260269

261270
## Session Lifecycle
262271

@@ -277,7 +286,7 @@ Use `pty_kill` with `cleanup=true` to remove completely.
277286
## Local Development
278287

279288
```bash
280-
git clone https://github.com/shekohex/opencode-pty.git
289+
git clone https://github.com/MBanucu/opencode-pty.git
281290
cd opencode-pty
282291
bun install
283292
bun run typecheck # Type check

0 commit comments

Comments
 (0)