Compare commits

..

6 Commits

Author SHA1 Message Date
0xmrpeter
90120c58fb fix: address code review findings — security, scope enforcement, auth flow
Critical fixes:
- C1: Use timingSafeEqual for JWT signature verification (prevent timing attacks)
- C2: Add requireScopes/requireRole preHandler to ALL routes per spec
- C3: Register auth routes with auth=false so refresh endpoint can accept expired JWTs

Important fixes:
- I1: Add pluginDependencies to SSE adapter for proper boot order
- I3: Log warnings on TokenStore save failures instead of swallowing
- I6: Remove duplicate system routes from server.ts (use v1-system.ts only)
- S6: Add event IDs to SSE connected event for reconnect support

Tests added:
- 14 auth integration tests covering middleware, JWT flow, refresh with expired
  tokens, revocation, scope overrides, token generation, /me endpoint

Entire-Checkpoint: 378950358515
2026-03-31 01:55:43 +07:00
0xmrpeter
2274166c73 feat(connectivity): add openacp remote command, instance discovery, QR codes
- Add instance-discovery utility to find running instances from registry
- Add openacp remote CLI command with token generation + link output
- Support 3 link formats: localhost, tunnel, custom scheme (openacp://)
- ASCII QR code in terminal via qrcode-terminal
- Flags: --role, --expire, --scopes, --name, --no-tunnel, --no-qr
- Auto-generated token names: remote-HHhMM-DD-MM-YYYY
- Auto-detect tunnel URL from health endpoint
2026-03-31 01:44:51 +07:00
0xmrpeter
da35c608cf feat(sse): add SSE adapter plugin for app client messaging
- Create @openacp/sse-adapter plugin implementing IChannelAdapter
- Add event serializer for OutgoingMessage → SSE format
- Add circular EventBuffer for reconnect support (Last-Event-ID)
- Add ConnectionManager for per-session SSE connection lifecycle
- Add Fastify routes: SSE stream, prompt, permission, cancel, command
- Register as core adapter + routes via ApiServerService
- Full middleware chain integration (same as Telegram adapter)
2026-03-31 01:42:33 +07:00
0xmrpeter
0a8ca373ed feat(auth): add JWT auth system with roles, scopes, token management
- Add auth types, role definitions (admin/operator/viewer), scope mappings
- Implement TokenStore (in-memory + JSON persist) with create/revoke/refresh/cleanup
- Implement JWT sign/verify/refresh using Node.js crypto (HMAC-SHA256)
- Extend auth middleware to support both secret token and JWT
- Add auth routes: generate token, list, revoke, refresh, /me
- Wire JWT secret and TokenStore into plugin lifecycle
- Separate jwt-secret file from api-secret for independent rotation
2026-03-31 01:40:07 +07:00
0xmrpeter
a64c0c3bb5 feat(api): complete Fastify migration - server factory, routes, service, auth stub, error handling
- Replace Node.js http with Fastify + @fastify/cors, swagger, rate-limit
- Migrate all routes to Fastify plugins under /api/v1/ prefix
- Add global error handler with consistent ApiError format
- Add auth middleware stub (secret token only, JWT in Plan 2)
- Add ApiServerService for plugin route registration
- Add backward-compat redirects from /api/ to /api/v1/
- Add new /api/v1/commands routes for command execution via API
- Preserve SSE manager, static server, all existing functionality
2026-03-31 01:35:38 +07:00
0xmrpeter
a1af91aad6 chore: add Fastify dependencies for API server refactor 2026-03-31 01:28:04 +07:00
496 changed files with 10382 additions and 74117 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -1,79 +0,0 @@
name: 🔌 Adapter / Plugin Request
description: Request a new platform adapter or plugin for OpenACP
title: "[Adapter]: "
labels: ["adapter", "enhancement"]
body:
- type: markdown
attributes:
value: |
Want OpenACP to support a new messaging platform or integration? Let us know!
- type: dropdown
id: type
attributes:
label: Request Type
options:
- New messaging platform adapter
- New AI agent support
- New tunnel provider
- Plugin / Integration
- Other
validations:
required: true
- type: input
id: platform-name
attributes:
label: Platform / Service Name
placeholder: "e.g. WhatsApp, Matrix, Microsoft Teams, Line"
validations:
required: true
- type: textarea
id: use-case
attributes:
label: Use Case
description: Why do you want this adapter? How would you use it?
placeholder: "My team uses [platform] daily and we want to control AI agents from there..."
validations:
required: true
- type: textarea
id: api-info
attributes:
label: API / SDK Information
description: Links to the platform's API docs, SDKs, or bot frameworks
placeholder: |
- API docs: https://...
- SDK: https://...
- Bot framework: https://...
- type: textarea
id: features
attributes:
label: Key Features Needed
description: Which OpenACP features are most important for this adapter?
placeholder: |
- [ ] Real-time streaming
- [ ] Permission buttons (approve/deny)
- [ ] Session management (threads/topics)
- [ ] Voice messages
- [ ] File sharing
- [ ] Code rendering with syntax highlighting
- type: dropdown
id: willing
attributes:
label: Would you be willing to contribute this?
options:
- "Yes, I'd like to build this adapter"
- "Yes, with guidance on the ChannelAdapter interface"
- "No, but I'd love to see it supported"
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional Context
description: Any technical constraints, rate limits, or special considerations

View File

@ -1,104 +0,0 @@
name: 🐛 Bug Report
description: Report a bug or unexpected behavior in OpenACP
title: "[Bug]: "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug! Please fill out the sections below so we can reproduce and fix it quickly.
- type: input
id: version
attributes:
label: OpenACP Version
description: Run `openacp --version` to get this
placeholder: "e.g. 2026.331.1"
validations:
required: true
- type: dropdown
id: platform
attributes:
label: Messaging Platform
description: "Which platform were you using? Note: Discord/Slack adapter issues may belong in their own repos."
options:
- Telegram
- Discord
- Slack
- REST API
- CLI
- Other
validations:
required: true
- type: input
id: agent
attributes:
label: AI Agent
description: "Which agent were you using? Run `openacp agents list` for exact name."
placeholder: "e.g. Claude Code, Codex, Gemini CLI, N/A"
validations:
required: true
- type: textarea
id: description
attributes:
label: Bug Description
description: A clear and concise description of what happened
placeholder: Tell us what went wrong
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: Step-by-step instructions to reproduce the behavior
placeholder: |
1. Start OpenACP with `openacp start`
2. Send message in Telegram "..."
3. Click approve on permission prompt
4. See error "..."
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected Behavior
description: What did you expect to happen?
validations:
required: true
- type: textarea
id: logs
attributes:
label: Logs / Error Output
description: Paste relevant logs. Run `openacp doctor` for diagnostics.
render: shell
- type: textarea
id: config
attributes:
label: Configuration
description: Relevant parts of your `~/.openacp/config.json` (remove secrets!)
render: json
- type: input
id: os
attributes:
label: Operating System
placeholder: "e.g. macOS 15.3, Ubuntu 24.04, Windows 11"
- type: input
id: node
attributes:
label: Node.js Version
placeholder: "e.g. 20.11.0"
- type: textarea
id: additional
attributes:
label: Additional Context
description: Screenshots, screen recordings, or any other context

View File

@ -1,11 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: ❓ Ask a Question
url: https://github.com/Open-ACP/OpenACP/discussions/categories/q-a
about: Use GitHub Discussions for questions. The community and maintainers can help you there.
- name: 💡 Share an Idea
url: https://github.com/Open-ACP/OpenACP/discussions/categories/ideas
about: Have a general idea or suggestion? Start a discussion first before opening a feature request.
- name: 📖 Documentation
url: https://openacp.gitbook.io/docs
about: Check the docs first — your answer might already be there.

View File

@ -1,75 +0,0 @@
name: 📝 Documentation Improvement
description: Suggest improvements to OpenACP documentation
title: "[Docs]: "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
Help us improve OpenACP docs! Whether it's a typo, missing info, or a new guide — we appreciate the feedback.
- type: dropdown
id: type
attributes:
label: Documentation Type
options:
- Fix typo / inaccuracy
- Missing documentation
- Improve existing docs (clarity, examples)
- New tutorial / guide
- API reference update
- Translation
validations:
required: true
- type: dropdown
id: location
attributes:
label: Documentation Location
description: Where is the documentation that needs updating?
options:
- README.md
- GitBook docs (openacp.gitbook.io)
- Contributing guide (GitBook)
- CLI help text
- Code comments / JSDoc
- Other
validations:
required: true
- type: input
id: page-url
attributes:
label: Page URL or File Path
description: Link to the specific page or file (if applicable)
placeholder: "e.g. https://openacp.gitbook.io/docs/getting-started"
- type: textarea
id: description
attributes:
label: What needs to change?
description: Describe the issue or improvement
placeholder: |
Current: "Run openacp start to begin"
Problem: Missing info about required env vars
Suggested: Add a section about setting TELEGRAM_BOT_TOKEN before first run
validations:
required: true
- type: textarea
id: proposed
attributes:
label: Proposed Content (optional)
description: If you have a draft of the improved text, paste it here
render: markdown
- type: dropdown
id: willing
attributes:
label: Would you be willing to submit a PR?
options:
- "Yes, I can write this"
- "Yes, with some guidance"
- "No, just reporting the issue"
validations:
required: true

View File

@ -1,74 +0,0 @@
name: ✨ Feature Request
description: Suggest a new feature or enhancement for OpenACP
title: "[Feature]: "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Have an idea to make OpenACP better? We'd love to hear it!
- type: dropdown
id: area
attributes:
label: Feature Area
description: Which part of OpenACP does this relate to?
options:
- Telegram adapter
- Discord adapter
- Slack adapter
- New platform adapter
- CLI
- REST API
- Session management
- Agent support
- Voice features
- Tunnel / Port forwarding
- Plugin system
- Configuration
- Security
- Performance
- Other
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or Motivation
description: What problem does this feature solve? Why do you need it?
placeholder: "I'm always frustrated when..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed Solution
description: How do you think this should work?
placeholder: Describe the ideal behavior, CLI commands, UI flow, etc.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: Any workarounds or alternative approaches you've considered?
- type: dropdown
id: willing
attributes:
label: Would you be willing to contribute this?
options:
- "Yes, I'd like to submit a PR"
- "Yes, with some guidance"
- "No, but I'd love to see it built"
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional Context
description: Mockups, screenshots, links to related issues or discussions

View File

@ -1,59 +0,0 @@
## Summary
<!-- What does this PR do? Keep it brief — 1-3 sentences. -->
## Related Issues
<!-- Link related issues: Closes #123, Fixes #456 -->
## Type of Change
- [ ] 🐛 Bug fix
- [ ] ✨ New feature
- [ ] 🔌 New adapter / plugin
- [ ] 📝 Documentation
- [ ] ♻️ Refactor (no functional change)
- [ ] ⚡ Performance improvement
- [ ] 🧪 Tests
- [ ] 🔧 CI / Build / Config
## Changes Made
<!-- Describe what you changed and why. Bullet points are fine. -->
-
## Testing
<!-- How did you test this? -->
- [ ] Ran `pnpm test` — all tests pass
- [ ] Tested manually with: <!-- which platform? Telegram / Discord / Slack -->
- [ ] Added new tests for this change
- [ ] No tests needed (explain why)
## Platform Impact
<!-- Which platforms does this affect? -->
- [ ] Telegram
- [ ] Discord
- [ ] Slack
- [ ] CLI
- [ ] REST API
- [ ] Web UI
- [ ] All / Core
## Screenshots / Recordings
<!-- If applicable — especially for UI changes or new adapter features -->
## Checklist
- [ ] My code follows the project's TypeScript conventions (ESM, `.js` extensions)
- [ ] I have updated relevant documentation (if needed)
- [ ] I have added/updated tests (if applicable)
- [ ] My changes don't introduce new warnings or errors
- [ ] I have run `pnpm build` successfully
- [ ] My changes are backward compatible with existing config and data formats
- [ ] If changing plugin API / PluginContext: I have updated `src/cli/plugin-template/`

7
.gitignore vendored
View File

@ -1,5 +1,3 @@
.DS_Store
# References (external/third-party code)
references/
node_modules/
@ -16,7 +14,4 @@ test/
built-in-plugins/
plugin-registry/
.worktrees/
.log
# OpenACP local workspace (contains secrets)
.openacp
.log

View File

@ -75,13 +75,13 @@ src/
All features are plugins. Core only provides infrastructure (ServiceRegistry, MiddlewareChain, EventBus, LifecycleManager). Plugins register services, commands, and middleware in their `setup()` hook.
- 19 middleware hook points (message:incoming, agent:beforePrompt, permission:beforeRequest, etc.)
- 18 middleware hook points (message:incoming, agent:beforePrompt, permission:beforeRequest, etc.)
- 9 permission types (events:read, services:register, commands:register, etc.)
- Per-plugin settings via SettingsManager (~/.openacp/plugins/<name>/settings.json)
### Adapter Patterns
- **Topics** (Telegram): Each session gets its own topic
- **Forum topics** (Telegram): Each session gets its own topic
- **Callback routing**: Permission buttons use `p:` prefix, command buttons use `c/` prefix
- **Response renderers**: Adapters render CommandResponse types (text, menu, list, confirm, error, silent) per platform
@ -95,10 +95,10 @@ Published as `@openacp/cli` on npm. Users install with `npm install -g @openacp/
## Versioning
Format: `YYYY.MMDD.<patch>` — e.g. `2026.327.1` is the first patch on March 27, 2026.
Format: `YYYY.MDD.<patch>` — e.g. `2026.327.1` is the first patch on March 27, 2026.
- `YYYY` — year
- `MMDD` — month (2-digit) + day (2-digit), leading zeros stripped by semver. Jan 5 = `105`, Mar 27 = `327`, Apr 1 = `401`, Dec 5 = `1205`
- `MDD` — month + day (no leading zeros, since semver strips them). Jan 5 = `15`, Mar 27 = `327`, Dec 5 = `1205`
- `<patch>` — sequential patch number for that day, starting from 1
## Documentation Sync

View File

@ -1,53 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a welcoming and respectful experience for everyone.
We pledge to act and interact in ways that contribute to an open, inclusive,
and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior:
- Trolling, insulting or derogatory comments, and personal attacks
- Public or private intimidation
- Publishing others' private information without explicit permission
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate or harmful.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
## Enforcement
Instances of unacceptable behavior may be reported to the community leaders
responsible for enforcement at **conduct@openacp.ai** <!-- TODO: @0xmrpeter — please replace with your preferred private email for CoC enforcement -->.
All complaints will be reviewed and investigated promptly and fairly. All
community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/),
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html).

View File

@ -1,167 +0,0 @@
# Contributing to OpenACP
Welcome! OpenACP is a self-hosted bridge connecting AI coding agents to messaging platforms. Contributions of all kinds are welcome — bug reports, features, docs, and tests.
Please read the [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.
---
## Development Setup
**Prerequisites**
- Node.js >= 20
- pnpm 10.5.0+ (`npm install -g pnpm`)
**Getting started**
```bash
git clone https://github.com/Open-ACP/OpenACP.git
cd OpenACP
pnpm install
pnpm build
```
**Development modes**
```bash
pnpm dev # tsc --watch (type-check + rebuild on change)
pnpm dev:loop # auto-restart dev server on change
```
**Running tests**
```bash
pnpm test # run all tests once
pnpm test:watch # watch mode
```
---
## Project Structure
```
src/
├── core/ # Core infrastructure
│ ├── config/ # Zod-validated config, migrations, editor
│ ├── agents/ # Agent instance, catalog, installer, store
│ ├── sessions/ # Session, session-manager, session-bridge, permission-gate
│ ├── plugin/ # Plugin system (LifecycleManager, ServiceRegistry, MiddlewareChain)
│ ├── commands/ # System chat commands (session, agents, admin, help, menu)
│ ├── adapter-primitives/ # Shared adapter framework (MessagingAdapter, StreamAdapter, etc.)
│ ├── utils/ # Logger, typed-emitter, file utilities
│ └── setup/ # First-run setup wizard
├── plugins/ # All platform adapters and service plugins
│ ├── telegram/ # Telegram adapter (grammY)
│ ├── speech/ # TTS/STT (Edge TTS, Groq STT)
│ ├── tunnel/ # Port forwarding (Cloudflare, ngrok, Bore, Tailscale)
│ ├── security/ # Access control, rate limiting
│ ├── api-server/ # REST API + SSE
│ ├── file-service/ # File I/O for agents
│ ├── notifications/ # Cross-session alerts
│ └── context/ # Conversation history
├── cli/
│ ├── commands/ # CLI commands (start, plugins, dev, etc.)
│ └── plugin-template/ # Scaffold for `openacp plugin create`
├── cli.ts # CLI entry point
├── main.ts # Server startup, plugin boot
└── index.ts # Public API exports
packages/
└── plugin-sdk/ # @openacp/plugin-sdk — types + testing utilities
ui/ # Web UI (React + Vite, separate pnpm project)
```
---
## Architecture Overview
OpenACP uses a **plugin-based architecture**. Core provides only infrastructure (ServiceRegistry, MiddlewareChain, EventBus, LifecycleManager) — all features are plugins.
```
User (Telegram/Slack) → ChannelAdapter → OpenACPCore → Session → AgentInstance (ACP subprocess)
```
- **LifecycleManager** boots plugins in dependency order and manages setup/teardown
- **ServiceRegistry** is the central service discovery layer — plugins register services, core accesses them via typed interfaces
- **MiddlewareChain** provides 18 hook points (e.g. `message:incoming`, `agent:beforePrompt`, `permission:beforeRequest`)
- **CommandRegistry** handles all chat commands from both core and plugins
For a complete architecture reference and AI-friendly codebase guide, see [`CLAUDE.md`](CLAUDE.md).
## Building a Plugin
Install the SDK:
```bash
npm install @openacp/plugin-sdk
```
Scaffold a new plugin:
```bash
openacp plugin create my-plugin
```
See [`packages/plugin-sdk/`](packages/plugin-sdk/) for the full API and [`src/cli/plugin-template/`](src/cli/plugin-template/) for the scaffold template.
---
## Code Style & Conventions
- **English only** — all code, comments, commit messages, and documentation must be in English
- **TypeScript strict mode** — all code must pass `tsc --noEmit`
- **ESM modules** — use `.js` extensions in all imports (even for `.ts` source files)
- **Zod** for config validation and schema definitions
- **Pino** for structured logging — no `console.log` in library code
- Use kebab-case for file names
- **Versioning format**: `YYYY.MDD.<patch>` — e.g. `2026.327.1` is the first patch on March 27 2026
---
## Testing Guidelines
- Framework: [vitest](https://vitest.dev/)
- Test files: `src/core/__tests__/`, `src/__tests__/` (integration), `src/plugins/*/` (plugin unit tests)
- Run with `pnpm test` before submitting a PR
- Test state machines, user flows end-to-end, error recovery, and concurrency
- Mock at boundaries only (AgentInstance, ChannelAdapter, SessionStore) — not internal classes
- Do not mock away real behavior to make tests pass
---
## Pull Request Process
1. **Fork** the repo and create a branch from `main`
2. **Branch naming**: use a prefix that matches the change type
- `feat/` — new feature
- `fix/` — bug fix
- `docs/` — documentation only
- `refactor/` — code cleanup without behavior change
3. **Implement** your change and write or update tests
4. **Commit** using [Conventional Commits](https://www.conventionalcommits.org/):
- `feat: add slack reaction support`
- `fix: reconnect on websocket timeout`
- `docs: update setup instructions`
5. **Push** and open a PR against `main`
6. **Update docs** — if your change adds or modifies a feature, update `README.md` and/or the `docs/` directory
7. **CI must pass** before a PR can be merged
8. At least one maintainer review is required
---
## Where to Start
- Browse [`good first issue`](https://github.com/Open-ACP/OpenACP/labels/good%20first%20issue) for beginner-friendly tasks
- Check [`help wanted`](https://github.com/Open-ACP/OpenACP/labels/help%20wanted) for tasks that need community help
- Join [GitHub Discussions](https://github.com/Open-ACP/OpenACP/discussions) for questions and ideas
---
## Reporting Issues
Use [GitHub Issues](https://github.com/Open-ACP/OpenACP/issues) to report bugs or request features. Please check for existing issues before opening a new one and include reproduction steps where applicable.
---
## License
By contributing, you agree that your contributions will be licensed under the [MIT License](LICENSE).

142
README.md
View File

@ -1,5 +1,3 @@
OpenACP — self-hosted bridge that connects 28+ AI coding agents (Claude Code, Codex, Gemini, Cursor) to Telegram, Discord & Slack. Your machine, your keys, your data.
<div align="center">
# OpenACP
@ -14,9 +12,7 @@ Send a message. The agent writes code. You see everything — in real time.
[![npm](https://img.shields.io/npm/v/@openacp/cli.svg)](https://www.npmjs.com/package/@openacp/cli)
[![Twitter Follow](https://img.shields.io/twitter/follow/openacp_ai?style=social)](https://x.com/openacp_ai)
[Documentation](https://openacp.gitbook.io/docs) · [Quick Start](#quick-start) · [Features](#features) · [Agents](#supported-agents) · [Contributing](CONTRIBUTING.md) · [Discussions](https://github.com/Open-ACP/OpenACP/discussions)
<img src="docs/images/banner.jpg" alt="OpenACP — Control AI coding agents from Telegram, Discord and Slack" width="100%" />
[Documentation](https://openacp.gitbook.io/docs) · [Quick Start](#quick-start) · [Features](#features) · [Agents](#supported-agents) · [Contributing](https://openacp.gitbook.io/docs/extending/contributing)
</div>
@ -38,85 +34,27 @@ AI Agent (Claude Code, Codex, Gemini, Cursor, ...)
Your Codebase
```
## Why OpenACP?
| Without OpenACP | With OpenACP |
|----------------|-------------|
| *"Its usage is currently focused on its dedicated terminal REPL and specific IDE integrations"* | Control from Telegram, Discord, or Slack — any device, anywhere |
| *"Codex Desktop App only works with local projects. It does not support development on remote hosts"* | Full remote development support — run agents on your server, manage from your phone |
| *"There's no way to trigger Claude Code sessions from external issue trackers"* | REST API for CI/CD integration and external triggers |
| *"Being able to use a proper mobile app UI would be much better than having to access sessions through ssh + tmux"* | Native Telegram/Discord UI — no SSH, no terminal on mobile |
| *"Cline is really burning up OpenRouter tokens and my wallet"* | Built-in usage tracking and monthly budget limits per session |
## Use Cases
- **Remote coding** — Tired of being chained to your desk to run Claude Code? Review PRs, fix bugs, and deploy from your phone via Telegram while away from your desk.
- **Team visibility** — Share a Discord channel where everyone sees what the AI agent is doing in real time — no more black-box coding sessions.
- **Multi-agent workflows** — Start with Claude Code for planning, switch to Codex for implementation, use Gemini for review — all in one chat thread, no reconfiguration.
- **CI/CD integration** — Trigger agent sessions from GitHub Actions or any issue tracker via the REST API.
- **Self-hosted AI gateway** — Keep API keys and code on your own infrastructure. No third-party cloud, no vendor lock-in.
- **Local LLM support** — Run agents against self-hosted models (Ollama, LM Studio) via ACP-compatible adapters. Your models, your data.
<div align="center">
<table>
<tr>
<td align="center"><img src="docs/images/menu.png" width="250" alt="OpenACP control panel showing session management, agent selection, and settings menu in Telegram" /><br /><b>Control Panel</b><br />Manage sessions, agents, and settings</td>
<td align="center"><img src="docs/images/agent-working.png" width="250" alt="AI coding agent reading files, planning changes, and writing code through OpenACP Telegram interface" /><br /><b>Agent at Work</b><br />Plans, reads files, writes code</td>
<td align="center"><img src="docs/images/menu.png" width="250" /><br /><b>Control Panel</b><br />Manage sessions, agents, and settings</td>
<td align="center"><img src="docs/images/agent-working.png" width="250" /><br /><b>Agent at Work</b><br />Plans, reads files, writes code</td>
</tr>
<tr>
<td align="center"><img src="docs/images/tool-calls.png" width="250" alt="Real-time tool call streaming showing agent actions like file reads, edits, and command execution" /><br /><b>Real-time Tool Calls</b><br />See every action the agent takes</td>
<td align="center"><img src="docs/images/skills.png" width="250" alt="OpenACP agent skills menu with options for brainstorming, TDD, debugging, and code review" /><br /><b>Agent Skills</b><br />Brainstorming, TDD, debugging & more</td>
<td align="center"><img src="docs/images/tool-calls.png" width="250" /><br /><b>Real-time Tool Calls</b><br />See every action the agent takes</td>
<td align="center"><img src="docs/images/skills.png" width="250" /><br /><b>Agent Skills</b><br />Brainstorming, TDD, debugging & more</td>
</tr>
</table>
</div>
## Installation
**Requirements:** Node.js 20+ (the installer handles this for you)
### macOS
```bash
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
```
### Linux
```bash
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
```
> Works on Debian/Ubuntu, Fedora/RHEL, Arch, and other distros. Also supports WSL (Windows Subsystem for Linux).
### Windows
Open PowerShell and run:
```powershell
powershell -c "irm https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.ps1 | iex"
```
> Requires PowerShell 5.1+ (built into Windows 10/11).
### Manual install via npm
If you already have Node.js 20+ installed:
## Quick Start
```bash
npm install -g @openacp/cli
openacp
# → Interactive setup wizard starts:
# → ? Choose your platform: Telegram / Discord / Slack
# → ? Enter your bot token: ********
# → ? Select workspace directory: ~/projects
# → ? Choose default AI agent: Claude Code
# → ✓ Configuration saved. Starting OpenACP...
# → 🚀 OpenACP is running. Send a message to your bot!
```
---
After installation, the **interactive setup wizard** walks you through everything:
The interactive setup wizard walks you through everything:
1. Choose your platform (Telegram, Discord, Slack, or multiple)
2. Connect your bot (token validation + auto-detection)
@ -145,14 +83,12 @@ That's it. Send a message to your bot and start coding.
- **Session persistence** — Sessions survive restarts, with configurable TTL
- **Permission control** — Approve or deny agent actions via buttons, with optional auto-approve
- **Real-time streaming** — See agent thinking, tool calls, and output as they happen
- **Agent switching** — Switch agents mid-conversation with `/switch`; history carries over automatically
### Developer Tools
- **Tunnel & port forwarding** — Expose local ports to the internet (Cloudflare, ngrok, bore, Tailscale)
- **Built-in file viewer** — Monaco Editor with syntax highlighting, diffs, and markdown preview
- **Session transfer** — Move sessions between terminal and chat (`/handoff`)
- **Agent switch** — Change which AI agent handles your session mid-conversation (`/switch`)
- **Voice & speech** — Send voice messages, get spoken responses (Groq STT + Edge TTS)
- **Usage tracking** — Token counts, cost reports, optional monthly budget limits
- **Context resume** — Resume sessions with full conversation history
@ -180,7 +116,7 @@ OpenACP uses the [ACP Registry](https://agentclientprotocol.com/get-started/regi
| [Cursor](https://www.cursor.com/) | binary | Cursor's coding agent |
| [Cline](https://github.com/cline/cline) | npx | Autonomous coding agent |
| [goose](https://github.com/block/goose) | binary | Open source AI agent by Block |
| Amp | binary | The frontier coding agent |
| [Amp](https://github.com/tao12345666333/amp-acp) | binary | The frontier coding agent |
| [Auggie CLI](https://www.augmentcode.com/) | npx | Augment Code's context engine |
| [Junie](https://www.jetbrains.com/) | binary | AI coding agent by JetBrains |
| [Kilo](https://github.com/kilocode/kilo) | npx | Open source coding agent |
@ -197,8 +133,7 @@ openacp agents install <name> # Install from registry
```bash
# Server
openacp # Start (first run = setup wizard)
openacp start / stop / restart # Daemon management
openacp status # Check daemon status
openacp start / stop / status # Daemon management
openacp logs # Tail daemon logs
# Configuration
@ -231,59 +166,6 @@ openacp tunnel list
| [API Reference](https://openacp.gitbook.io/docs/api-reference) | CLI commands, REST API, config schema, env vars |
| [Troubleshooting](https://openacp.gitbook.io/docs/troubleshooting) | Common issues and FAQ |
## Known Limitations
- **Early stage** — OpenACP is under active development; expect breaking changes between minor versions
- **Single user** — Currently designed for individual use; multi-user/team support is planned
- **Remote host** — Agents run on the same machine as OpenACP; to use on a remote server, install OpenACP on that server
- **Agent availability** — Some agents require their own API keys and local installation
- **Platform features** — Not all messaging platform features are supported equally (e.g., Slack threads vs Telegram forum topics)
- **No Windows daemon** — Daemon mode (auto-start on boot) currently supports macOS and Linux only
## FAQ
### Why use Telegram or Discord instead of just the terminal?
Most AI coding agents are locked to a terminal REPL or IDE. OpenACP lets you send messages, review code diffs, approve or deny actions, and monitor progress from any device — phone, tablet, or browser — without opening a laptop.
### How is OpenACP different from MCP?
MCP (Model Context Protocol) is a standard for giving AI models access to tools and data sources. OpenACP uses the **Agent Client Protocol (ACP)** to manage full coding agent *sessions* — starting agents, streaming output, handling permissions, and routing results to your messaging platform. The two protocols are complementary: your agents can use MCP tools while OpenACP manages the session layer.
### Can I auto-approve agent actions?
Yes. By default, OpenACP shows a permission button for destructive actions. You can configure [auto-approve rules](https://openacp.gitbook.io/docs/using-openacp) to skip confirmation for specific action types (e.g., read-only operations) while still requiring approval for file writes or shell commands.
### How do I control API spending?
Set a monthly budget limit in your config. OpenACP tracks token usage and cost in real time and will pause the agent when the limit is reached. Run `openacp config` to set limits per session.
### Can I use a local or self-hosted LLM?
Yes, if the model has a compatible agent CLI. Any agent that implements the ACP protocol can be registered. Community adapters exist for Ollama and LM Studio — run `openacp agents` to browse available options.
### What happens if the agent gets stuck or the chat hangs?
Use `/cancel` in your chat to stop the current session. Run `openacp doctor` to check for connectivity or configuration issues. OpenACP's session persistence means you can resume with full context intact after a restart.
### Does OpenACP send my code to the cloud?
No. OpenACP runs entirely on your machine. AI agents connect directly to your chosen provider using your own API keys. Nothing is routed through OpenACP servers.
### Can I use multiple AI agents at the same time?
Each session uses one agent, but you can run multiple sessions simultaneously — one per thread/topic in your chat. Switch agents between sessions or start a new session with a different agent at any time.
### Is OpenACP free?
Yes. OpenACP is MIT-licensed and free to self-host. You only pay for the AI provider API keys you choose to use.
### How do I update OpenACP?
```bash
npm update -g @openacp/cli
```
## Security
OpenACP grants AI agents access to your filesystem and shell. Before using in production:
- Run in a sandboxed environment or container when possible
- Review agent permissions — use the built-in permission gate to approve/deny actions
- Never expose your OpenACP instance to the public internet without authentication
- Keep your bot tokens secret — rotate them if compromised
- See the [Security guide](https://openacp.gitbook.io/docs/self-hosting/security) for hardening recommendations
## Star History
<a href="https://star-history.com/#Open-ACP/OpenACP&Date">
@ -296,7 +178,11 @@ OpenACP grants AI agents access to your filesystem and shell. Before using in pr
## Contributing
We welcome contributions! See the [contributing guide](CONTRIBUTING.md) for development setup, testing conventions, and PR process. Have questions? Start a thread on [GitHub Discussions](https://github.com/Open-ACP/OpenACP/discussions).
We welcome contributions! See the [contributing guide](https://openacp.gitbook.io/docs/extending/contributing) for development setup, testing conventions, and PR process.
## Follow Us
[![Twitter Follow](https://img.shields.io/twitter/follow/openacp_ai?style=social)](https://x.com/openacp_ai)
## License

BIN
docs/.DS_Store vendored

Binary file not shown.

View File

@ -18,9 +18,9 @@ Choose the path that fits you:
| I want to... | Start here |
|---|---|
| **Understand what OpenACP does** | [What is OpenACP?](getting-started/what-is-openacp.md) |
| **Install and start chatting** with an AI agent | [Quick Start](getting-started/quick-start.md) |
| **Build plugins & adapters** for OpenACP | [For Contributors](getting-started/for-contributors.md) |
| **Chat with AI agents** via Telegram/Discord | [Quick Start for Users](getting-started/for-users.md) |
| **Self-host OpenACP** on my machine | [Quick Start for Developers](getting-started/for-developers.md) |
| **Build plugins & adapters** for OpenACP | [Quick Start for Contributors](getting-started/for-contributors.md) |
Or start with [What is OpenACP?](getting-started/what-is-openacp.md) to understand the big picture.

View File

@ -39,13 +39,9 @@
* [Overview](features/README.md)
* [Tunnel & Port Forwarding](features/tunnel.md)
* [Context Resume](features/context-resume.md)
* [Output Modes](features/output-modes.md)
* [Usage & Budget](features/usage-and-budget.md)
* [Session Persistence](features/session-persistence.md)
* [Session Handoff](features/session-handoff.md)
* [Agent Switch](features/agent-switch.md)
* [Workspaces](features/multi-instance.md)
* [App Connectivity](features/app-connectivity.md)
* [Doctor Diagnostics](features/doctor.md)
* [Assistant Mode](features/assistant-mode.md)

View File

@ -4,28 +4,6 @@ All commands are invoked as `openacp <command> [subcommand] [options]`. Every co
---
## JSON Output
Many commands accept a `--json` flag for machine-readable output. When `--json` is passed:
- Output is a single line of valid JSON on stdout
- Exit code `0` for success, non-zero for errors
- All progress indicators and ANSI codes are suppressed
**Success envelope (exit 0):**
```json
{ "success": true, "data": { ... } }
```
**Error envelope (exit non-zero):**
```json
{ "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable description" } }
```
Commands that support `--json` are noted in their options tables below.
---
## adopt
Transfers an existing external agent session into OpenACP so it appears as a messaging thread. Requires a running daemon.
@ -41,34 +19,14 @@ openacp adopt <agent> <session_id> [--cwd <path>] [--channel <name>]
|---|---|
| `--cwd <path>` | Working directory for the session (default: current directory) |
| `--channel <name>` | Target channel adapter, e.g. `telegram`, `discord` (default: first registered) |
| `--json` | Output result as JSON |
**Examples**
```bash
openacp adopt claude abc123-def456
openacp adopt claude abc123 --cwd /path/to/project
openacp adopt claude abc123 --channel discord
openacp adopt claude abc123 --json
```
**JSON output** (`data` shape):
```json
{ "sessionId": "...", "threadId": "...", "agent": "claude", "status": "active" }
```
---
## attach
Connects to a running daemon and displays live status with log tailing. Useful for monitoring a daemon instance without opening a separate terminal.
**Usage**
```
openacp attach
```
Shows the daemon's current status (uptime, sessions, adapters, tunnel) and tails the log file. Press Ctrl+C to detach.
---
## agents
@ -87,12 +45,6 @@ Lists all installed agents and agents available to install from the registry.
**Example**
```bash
openacp agents
openacp agents --json
```
**JSON output** (`data` shape):
```json
{ "agents": [{ "key": "claude", "name": "Claude Code", "version": "1.0.0", "distribution": "npm", "description": "...", "installed": true, "available": true, "missingDeps": [] }] }
```
### agents install
@ -100,23 +52,16 @@ openacp agents --json
Installs an agent from the ACP Registry. Automatically installs the handoff integration if the agent supports it.
```
openacp agents install <name> [--force] [--json]
openacp agents install <name> [--force]
```
| Flag | Description |
|---|---|
| `--force` | Reinstall even if already installed |
| `--json` | Output result as JSON |
```bash
openacp agents install claude
openacp agents install gemini --force
openacp agents install claude --json
```
**JSON output** (`data` shape):
```json
{ "key": "claude", "version": "1.0.0", "installed": true }
```
### agents uninstall
@ -124,21 +69,11 @@ openacp agents install claude --json
Removes an installed agent and its handoff integration (if any).
```
openacp agents uninstall <name> [--json]
openacp agents uninstall <name>
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
```bash
openacp agents uninstall gemini
openacp agents uninstall gemini --json
```
**JSON output** (`data` shape):
```json
{ "key": "gemini", "uninstalled": true }
```
### agents info
@ -146,22 +81,12 @@ openacp agents uninstall gemini --json
Shows version, distribution type, command, setup steps, and installation status for an agent.
```
openacp agents info <name> [--json]
openacp agents info <name>
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
```bash
openacp agents info cursor
openacp agents info claude
openacp agents info claude --json
```
**JSON output** (`data` shape):
```json
{ "key": "claude", "name": "Claude Code", "version": "1.0.0", "distribution": "npm", "description": "...", "installed": true, "binaryPath": "/usr/local/bin/claude", "command": "claude", "registryId": "claude" }
```
### agents run
@ -194,11 +119,9 @@ openacp agents refresh
Interacts with a running OpenACP daemon over the local REST API. Requires a running daemon (`openacp start`).
All `api` subcommands support `--json` for machine-readable output.
**Usage**
```
openacp api <subcommand> [args] [--json]
openacp api <subcommand> [args]
```
### api cancel
@ -228,12 +151,12 @@ openacp api config
openacp api config set <key> <value>
```
### api bypass
### api dangerous
Enables or disables bypass permissions for a session. When enabled, the agent runs destructive commands without confirmation prompts.
Enables or disables dangerous mode for a session. When enabled, the agent runs destructive commands without confirmation prompts.
```
openacp api bypass <session-id> on|off
openacp api dangerous <session-id> on|off
```
### api delete-topic
@ -391,18 +314,12 @@ openacp config set <key> <value>
`openacp config` (no args) opens an interactive terminal editor. When the daemon is running, changes are applied live via the API; otherwise the config file is edited directly.
`openacp config set` applies a single value by dot-notation path. Values are JSON-parsed if possible, otherwise treated as strings. Supports `--json` for scripted use.
`openacp config set` applies a single value by dot-notation path. Values are JSON-parsed if possible, otherwise treated as strings.
```bash
openacp config set defaultAgent claude
openacp config set security.maxConcurrentSessions 5
openacp config set channels.telegram.botToken "123:ABC"
openacp config set defaultAgent gemini --json
```
**JSON output for `config set`** (`data` shape):
```json
{ "path": "defaultAgent", "value": "gemini", "needsRestart": false }
```
---
@ -413,21 +330,12 @@ Runs system diagnostics. Checks config validity, agent availability, dependencie
**Usage**
```
openacp doctor [--dry-run] [--json]
openacp doctor [--dry-run]
```
| Flag | Description |
|---|---|
| `--dry-run` | Report issues only; do not apply any fixes |
| `--json` | Output result as JSON (implies `--dry-run`; always exits 0 — check `summary.failed` for health) |
**JSON output** (`data` shape):
```json
{
"categories": [{ "name": "Config", "results": [{ "status": "pass", "message": "Config is valid" }] }],
"summary": { "passed": 5, "warnings": 1, "failed": 0 }
}
```
---
@ -437,22 +345,12 @@ Installs a plugin from npm into `~/.openacp/plugins/`. Supports built-in plugins
**Usage**
```
openacp install <package>[@version] [--json]
openacp install <package>[@version]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
```bash
openacp install @openacp/adapter-discord
openacp install @myorg/translator@1.2.0
openacp install @openacp/adapter-discord --json
```
**JSON output** (`data` shape):
```json
{ "plugin": "@openacp/adapter-discord", "version": "1.0.0", "installed": true }
```
This is an alias for `openacp plugin add`. See [plugin install](#plugin-install) for details.
@ -472,7 +370,6 @@ openacp integrate <agent> --uninstall
```bash
openacp integrate claude
openacp integrate claude --uninstall
openacp integrate opencode
```
---
@ -538,25 +435,15 @@ Installs a plugin package. Works with both built-in plugins and community plugin
**Usage**
```
openacp plugin add <package>[@version] [--json]
openacp plugin install <package>[@version] [--json]
openacp plugin add <package>[@version]
openacp plugin install <package>[@version]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**Examples**
```bash
openacp plugin add @openacp/adapter-discord
openacp plugin add @myorg/translator@1.2.0
openacp plugin install my-plugin
openacp plugin add @openacp/adapter-discord --json
```
**JSON output** (`data` shape):
```json
{ "plugin": "@openacp/adapter-discord", "version": "1.0.0", "installed": true }
```
Community plugins are installed via `npm install` into `~/.openacp/plugins/node_modules/`. The plugin's `install()` hook is called if defined.
@ -585,59 +472,16 @@ Enables or disables an installed plugin without removing it. Disabled plugins ar
**Usage**
```
openacp plugin enable <name> [--json]
openacp plugin disable <name> [--json]
openacp plugin enable <name>
openacp plugin disable <name>
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**Examples**
```bash
openacp plugin disable @myorg/translator
openacp plugin enable @myorg/translator
openacp plugin enable @myorg/translator --json
```
**JSON output** (`data` shape):
```json
{ "plugin": "@myorg/translator", "enabled": true }
```
---
## remote
Generates access links for connecting app clients to a running OpenACP instance. Displays local URL, tunnel URL (if enabled), app deep link, and a QR code.
**Usage**
```
openacp remote [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON (no QR code printed) |
The generated link includes a single-use access code valid for 30 minutes. The app exchanges this code for a JWT token on first use.
**Example output**
```
Local: http://127.0.0.1:21420
Tunnel: https://abc.trycloudflare.com
App: openacp://connect?host=abc.trycloudflare.com&code=xyz123
[QR code]
```
**JSON output** (`data` shape):
```json
{ "code": "xyz123", "name": "my-instance", "role": "owner", "expiresAt": "2026-04-02T13:00:00Z", "urls": { "local": "http://127.0.0.1:21420", "tunnel": "https://abc.trycloudflare.com", "app": "openacp://connect?host=abc.trycloudflare.com&code=xyz123" } }
```
See [App Connectivity](../features/app-connectivity.md) for the full guide.
---
## plugins
@ -646,16 +490,7 @@ Lists all plugins installed in `~/.openacp/plugins/`.
**Usage**
```
openacp plugins [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "plugins": [{ "name": "@openacp/adapter-discord", "version": "1.0.0", "enabled": true, "source": "npm", "description": "Discord adapter" }] }
openacp plugins
```
---
@ -675,56 +510,21 @@ Prompts for confirmation before proceeding.
## restart
Restarts the daemon. By default uses the same run mode as configured; use `--foreground` or `--daemon` to override.
**Usage**
```
openacp restart [--foreground | --daemon] [--json]
```
| Flag | Description |
|---|---|
| `--foreground` | Restart in foreground mode (not compatible with `--json`) |
| `--daemon` | Restart as background daemon |
| `--json` | Output result as JSON (always uses daemon mode) |
There is no standalone `restart` command. Use `openacp api restart` to restart a running daemon, or stop and start it manually:
```bash
openacp restart
openacp restart --daemon --json
```
**JSON output** (`data` shape):
```json
{ "pid": 12345, "instanceId": "global", "dir": "/Users/alice/.openacp" }
openacp stop && openacp start
```
---
## start
Starts OpenACP. Requires an existing config (run `openacp` first to set up).
Starts OpenACP as a background daemon. Requires an existing config (run `openacp` first to set up).
**Usage**
```
openacp start [options]
```
**Options**
| Flag | Description |
|---|---|
| `--foreground` | Force foreground mode regardless of config |
| `--daemon` | Force daemon mode regardless of config |
| `--local` | Use local `.openacp/` instance in the current directory |
| `--global` | Use the global `~/.openacp/` instance |
| `--dir <path>` | Use a specific instance directory |
| `--name <id>` | Give the instance a name |
| `--from <source>` | Clone settings from an existing instance |
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "pid": 12345, "instanceId": "global", "dir": "/Users/alice/.openacp" }
openacp start
```
---
@ -735,23 +535,7 @@ Shows whether the OpenACP daemon is running and its PID.
**Usage**
```
openacp status [--all] [--id <id>] [--json]
```
| Flag | Description |
|---|---|
| `--all` | Show status of all registered instances, not just the current one |
| `--id <id>` | Show status of a specific instance |
| `--json` | Output result as JSON |
**JSON output** (`data` shape — all instances):
```json
{ "instances": [{ "id": "global", "name": "my-instance", "status": "running", "pid": 12345, "dir": "/Users/alice/.openacp", "mode": "daemon", "channels": ["telegram"], "apiPort": 21420, "tunnelPort": null }] }
```
**JSON output** (`data` shape — single instance with `--id`):
```json
{ "id": "global", "name": "my-instance", "status": "running", "pid": 12345, "dir": "/Users/alice/.openacp", "mode": "daemon", "channels": ["telegram"], "apiPort": 21420, "tunnelPort": null }
openacp status
```
---
@ -762,16 +546,7 @@ Sends a stop signal to the running daemon.
**Usage**
```
openacp stop [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "stopped": true, "pid": 12345 }
openacp stop
```
---
@ -790,22 +565,12 @@ openacp tunnel <subcommand> [args]
Creates a tunnel to a local port.
```
openacp tunnel add <port> [--label <name>] [--session <id>] [--json]
openacp tunnel add <port> [--label <name>] [--session <id>]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
```bash
openacp tunnel add 3000
openacp tunnel add 8080 --label "dev server"
openacp tunnel add 3000 --json
```
**JSON output** (`data` shape):
```json
{ "port": 3000, "publicUrl": "https://abc.trycloudflare.com" }
```
### tunnel list
@ -813,16 +578,7 @@ openacp tunnel add 3000 --json
Lists all active tunnels with their ports, labels, and public URLs.
```
openacp tunnel list [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "tunnels": [{ "port": 3000, "label": "dev server", "publicUrl": "https://abc.trycloudflare.com", "status": "active" }] }
openacp tunnel list
```
### tunnel stop
@ -830,16 +586,7 @@ openacp tunnel list [--json]
Stops the tunnel for a specific local port.
```
openacp tunnel stop <port> [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "port": 3000, "stopped": true }
openacp tunnel stop <port>
```
### tunnel stop-all
@ -847,16 +594,7 @@ openacp tunnel stop <port> [--json]
Stops all user tunnels.
```
openacp tunnel stop-all [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "stopped": true }
openacp tunnel stop-all
```
---
@ -867,21 +605,11 @@ Removes an adapter plugin.
**Usage**
```
openacp uninstall <package> [--json]
openacp uninstall <package>
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
```bash
openacp uninstall @openacp/adapter-discord
openacp uninstall @openacp/adapter-discord --json
```
**JSON output** (`data` shape):
```json
{ "plugin": "@openacp/adapter-discord", "uninstalled": true }
```
---
@ -904,42 +632,16 @@ Running `openacp` with no arguments starts the server. On first run, the setup w
- `foreground` — runs in the current terminal.
- `daemon` — spawns a background process and exits.
If a daemon is already running, `openacp` shows a rich status display with an interactive menu instead of an error:
- **r** — restart the daemon
- **f** — restart in foreground mode
- **s** — show full status
- **l** — tail logs
- **q** — quit
The startup display also shows which instance is active (global vs. local) and prints hints when a local instance is available but the global is being used.
`openacp --foreground` forces foreground mode regardless of config.
---
## version
## --version / -v
Prints the installed version. Also available as `--version` / `-v`.
**Usage**
```
openacp version [--json]
openacp --version
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON |
Prints the installed version.
```bash
openacp --version
openacp version --json
```
**JSON output** (`data` shape):
```json
{ "version": "2026.401.1" }
```
---

View File

@ -31,7 +31,7 @@ Channel adapters. Each adapter key under `channels` is an object. The built-in T
| `channels.discord.forumChannelId` | string \| null | `null` | Forum channel ID for session threads |
| `channels.discord.notificationChannelId` | string \| null | `null` | Channel ID for system notifications |
| `channels.discord.assistantThreadId` | string \| null | `null` | Thread ID for the Assistant |
| `channels.discord.outputMode` | `"low"` \| `"medium"` \| `"high"` | `"medium"` | Adapter-level output detail. Overridden per session via `/outputmode session`. 3-level cascade: session → adapter → global → `"medium"`. The legacy key `displayVerbosity` is auto-migrated on startup. |
| `channels.discord.outputMode` | `"low"` \| `"medium"` \| `"high"` | `"medium"` | Controls message verbosity. The legacy key `displayVerbosity` is accepted for backward compatibility. |
### channels.slack.*
@ -80,14 +80,6 @@ Map of named agent configurations. Each key is an agent name used in `defaultAge
---
## outputMode
| Field | Type | Default | Description |
|---|---|---|---|
| `outputMode` | `"low"` \| `"medium"` \| `"high"` | `"medium"` | Global default output mode. Overridden per adapter via `channels.<name>.outputMode` and per session via `/outputmode session`. See [Output Modes](../features/output-modes.md). |
---
## defaultAgent
| Field | Type | Default | Description |
@ -163,11 +155,14 @@ Map of named agent configurations. Each key is an agent name used in `defaultAge
| Field | Type | Default | Description |
|---|---|---|---|
| `tunnel.enabled` | boolean | `false` | Enable the built-in tunnel service. When `true`, the tunnel auto-starts on server boot with keepalive monitoring. |
| `tunnel.enabled` | boolean | `false` | Enable the built-in tunnel service |
| `tunnel.port` | number | `3100` | Default local port the tunnel service listens on |
| `tunnel.provider` | `"cloudflare"` \| `"ngrok"` \| `"bore"` \| `"tailscale"` | `"cloudflare"` | Tunnel provider |
| `tunnel.options` | object | `{}` | Provider-specific options (passed through to the tunnel process) |
| `tunnel.maxUserTunnels` | number | `5` | Maximum number of simultaneous user-created tunnels |
| `tunnel.storeTtlMinutes` | number | `60` | Minutes before expired tunnel entries are cleaned up |
| `tunnel.auth.enabled` | boolean | `false` | Require authentication to access tunnel endpoints |
| `tunnel.auth.token` | string | — | Auth token for tunnel access (when `tunnel.auth.enabled` is true) |
---
@ -203,23 +198,6 @@ Map of named agent configurations. Each key is an agent name used in `defaultAge
---
## agentSwitch
Controls the behavior of the `/switch` command.
| Field | Type | Default | Description |
|---|---|---|---|
| `agentSwitch.labelHistory` | boolean | `true` | When `true`, agent names are prepended to messages in the conversation history injected into the new agent during a switch. Helps the incoming agent distinguish which AI produced which response. |
**Example**
```json
"agentSwitch": {
"labelHistory": true
}
```
---
## integrations
Tracks installed agent integrations (managed automatically by `openacp agents install` / `openacp integrate`).

View File

@ -25,7 +25,6 @@ All overrides are applied before Zod schema validation, so the final config is a
| `OPENACP_SPEECH_STT_PROVIDER` | `speech.stt.provider` | string | Active speech-to-text provider name |
| `OPENACP_SPEECH_GROQ_API_KEY` | `speech.stt.providers.groq.apiKey` | string | API key for the Groq STT provider |
| `OPENACP_CONFIG_PATH` | — | string | Override the config file path (default: `~/.openacp/config.json`) |
| `OPENACP_INSTANCE_ROOT` | — | string | Set the instance root directory. Overrides auto-detection and CLI flags. See [Multi-Instance](../features/multi-instance.md). |
## Plugin-Level Environment Variables

View File

@ -4,28 +4,19 @@ The OpenACP daemon exposes a local HTTP API used by the CLI and the web dashboar
**Base URL:** `http://127.0.0.1:21420` (configurable via `api.host` and `api.port`)
**Auth:** Two-tier authentication:
1. **Secret token** — from `~/.openacp/api-secret` (full admin access)
2. **JWT access token** — scoped, revokable tokens issued by the auth system
**Auth:** Bearer token from `~/.openacp/api-secret`
```bash
# Using secret token
TOKEN=$(cat ~/.openacp/api-secret)
curl -H "Authorization: Bearer $TOKEN" http://localhost:21420/api/sessions
# Using JWT token
curl -H "Authorization: Bearer $JWT" http://localhost:21420/api/sessions
```
The secret file is created automatically with mode `0600` on first start. Protect it like an SSH private key.
**Exempt from auth:** `GET /api/health`, `GET /api/version`.
**Exempt from auth:** `GET /api/health`, `GET /api/version`, `GET /api/events` (SSE uses query param `?token=`).
**Body size limit:** 1 MB.
**API documentation:** Swagger UI is available at `/docs` when the server is running.
---
## Health & System
@ -130,7 +121,7 @@ Lists all sessions (active, finished, cancelled, error).
"name": "Fix login bug",
"workspace": "/home/user/myproject",
"createdAt": "2026-03-25T10:00:00.000Z",
"bypassPermissions": false,
"dangerousMode": false,
"queueDepth": 0,
"promptRunning": true,
"lastActiveAt": "2026-03-25T10:05:00.000Z"
@ -161,7 +152,7 @@ Returns details for a single session.
"name": "Fix login bug",
"workspace": "/home/user/myproject",
"createdAt": "2026-03-25T10:00:00.000Z",
"bypassPermissions": false,
"dangerousMode": false,
"queueDepth": 1,
"promptRunning": false,
"threadId": "12345",
@ -261,9 +252,9 @@ curl -X POST \
---
### PATCH /api/sessions/:id/bypass
### PATCH /api/sessions/:id/dangerous
Enables or disables bypass permissions for a session.
Enables or disables dangerous mode for a session.
**Request body**
```json
@ -272,7 +263,7 @@ Enables or disables bypass permissions for a session.
**Response**
```json
{ "ok": true, "bypassPermissions": true }
{ "ok": true, "dangerousMode": true }
```
```bash
@ -280,7 +271,7 @@ curl -X PATCH \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled":true}' \
http://localhost:21420/api/sessions/sess_abc123/bypass
http://localhost:21420/api/sessions/sess_abc123/dangerous
```
---
@ -625,159 +616,6 @@ curl -X POST \
---
## Session Config
### GET /api/sessions/:id/config
Returns the agent-declared config options for a session (modes, models, toggles).
**Response**
```json
{
"configOptions": [
{
"id": "mode",
"name": "Mode",
"type": "select",
"category": "general",
"currentValue": "code",
"options": [
{ "value": "code", "label": "Code" },
{ "value": "architect", "label": "Architect" }
]
}
]
}
```
---
### PUT /api/sessions/:id/config/:configId
Updates a config option value for a session.
**Request body**
```json
{ "value": "architect" }
```
**Response**
```json
{ "ok": true, "configId": "mode", "value": "architect" }
```
---
## Authentication
### POST /api/v1/auth/tokens
Creates a new JWT access token. Requires secret token authentication.
**Request body**
```json
{ "name": "my-app", "role": "operator" }
```
**Response**
```json
{
"token": "eyJhbG...",
"id": "tok_abc123",
"name": "my-app",
"role": "operator",
"expiresAt": "2026-04-08T10:00:00.000Z"
}
```
---
### GET /api/v1/auth/tokens
Lists all active tokens (secret token auth required).
**Response**
```json
{
"tokens": [
{
"id": "tok_abc123",
"name": "my-app",
"role": "operator",
"createdAt": "2026-04-01T10:00:00.000Z",
"lastUsedAt": "2026-04-01T12:00:00.000Z"
}
]
}
```
---
### DELETE /api/v1/auth/tokens/:id
Revokes a token by ID. Requires secret token authentication.
**Response**
```json
{ "ok": true }
```
---
### GET /api/v1/auth/me
Returns information about the current token (works with both secret and JWT).
**Response**
```json
{
"type": "jwt",
"role": "operator",
"scopes": ["sessions:read", "sessions:write", "agents:read"],
"tokenId": "tok_abc123"
}
```
---
### POST /api/v1/auth/codes
Generates a one-time access code (for app connectivity). Requires secret token auth.
**Response**
```json
{
"code": "abc123def456",
"expiresAt": "2026-04-01T10:30:00.000Z"
}
```
The code is valid for 30 minutes and can be used exactly once.
---
### POST /api/v1/auth/exchange
Exchanges a one-time code for a JWT token. No prior authentication required.
**Request body**
```json
{ "code": "abc123def456" }
```
**Response**
```json
{
"token": "eyJhbG...",
"role": "operator",
"expiresAt": "2026-04-08T10:00:00.000Z"
}
```
Returns `401` if the code is expired or already used.
---
## Server-Sent Events
### GET /api/events
@ -788,16 +626,4 @@ SSE stream of real-time daemon events. Auth via query parameter (EventSource can
GET /api/events?token=<api-secret>
```
Returns a persistent SSE connection. Events include session lifecycle changes, agent output, and health pings (every 30 seconds).
### GET /api/v1/sse/sessions/:id/stream
Per-session SSE stream. Requires JWT authentication via query parameter.
```
GET /api/v1/sse/sessions/:id/stream?token=<jwt>
```
Streams only events for the specified session. Supports reconnect replay — if fewer than 100 events were missed, they are replayed on reconnection. Multiple clients can connect to the same session stream simultaneously.
**Event types**: `agent:event`, `session:updated`, `permission:request`, `health`.
Returns a persistent SSE connection. Events include session lifecycle changes, agent output, and health pings.

View File

@ -92,7 +92,7 @@ interface SecurityService {
}
```
**Commands**: `/bypass on|off` -- toggle auto-approve mode for all permissions.
**Commands**: `/dangerous on|off` -- toggle auto-approve mode for all permissions.
**Config**: Uses core `config.json` security section (`allowedUserIds`, `maxConcurrentSessions`).
@ -268,13 +268,13 @@ interface ContextService {
### @openacp/api-server
REST API, Server-Sent Events, and authentication for external integrations.
REST API and Server-Sent Events for external integrations.
- **Service**: `api-server` (implements `ApiServerService`)
- **Service**: `api-server`
- **Dependencies**: `@openacp/security`
- **Permissions**: `services:register`, `kernel:access`, `events:read`
**What it does**: Exposes a Fastify-based REST API with schema validation (Zod), Swagger/OpenAPI documentation, CORS, and rate limiting. Provides session management, prompt delivery, agent events via SSE, JWT authentication, and file viewer routes. Plugins can register additional routes via `ApiServerService.registerPlugin()`.
**What it does**: Exposes a REST API for managing sessions, sending prompts, and streaming agent events via SSE. Enables future Web UI integration. Also exposes plugin management endpoints.
**Settings**:
@ -282,39 +282,17 @@ REST API, Server-Sent Events, and authentication for external integrations.
|-----|------|-------------|
| `port` | number | HTTP port (default: `21420`) |
**Key capabilities**:
**API endpoints**:
- **Structured routes** — `/api/v1/*` endpoints for sessions, agents, config, system, commands, and auth
- **JWT authentication** — two-tier auth with secret token (master key) and scoped JWT access tokens
- **SSE streaming** — real-time session events, agent output, and health pings via `GET /api/v1/sse/sessions/:id/stream`
- **File viewer** — serves file, diff, and output viewer routes (merged from the former standalone viewer server)
- **Plugin extensibility** — plugins register additional Fastify routes via the `ApiServerService`
- **Swagger UI** — auto-generated API documentation at `/docs`
See the [REST API reference](../api-reference/rest-api.md) for the full endpoint list.
---
### SSE Manager (part of @openacp/api-server)
The SSE (Server-Sent Events) manager is integrated into the API server plugin rather than being a separate plugin. It provides real-time event streaming for app clients.
**What it does**: Broadcasts session lifecycle events, agent output, and health pings over SSE connections. Supports per-session filtering and automatic cleanup on disconnect.
**Event types**:
| Event | Description |
|-------|-------------|
| `session:created` | A new session was created |
| `session:updated` | Session state changed (status, name, etc.) |
| `session:deleted` | A session was destroyed |
| `agent:event` | Agent output (text, tool calls, errors) |
| `permission:request` | A permission request is pending |
| `health` | Periodic health ping (every 30s) with memory and uptime stats |
**Connection**: `GET /api/v1/sse/sessions/:id/stream?token=<jwt>` for per-session streams, or `GET /api/events?token=<api-secret>` for all events.
**Reconnect support**: A 100-event circular buffer per session enables replay on reconnect — if the client missed fewer than 100 events, they are replayed on reconnection.
| Endpoint | Description |
|----------|-------------|
| `GET /api/plugins` | List all plugins |
| `GET /api/plugins/:name` | Plugin details + settings |
| `PUT /api/plugins/:name/settings` | Update plugin settings |
| `POST /api/plugins/:name/enable` | Enable a plugin |
| `POST /api/plugins/:name/disable` | Disable a plugin |
| `GET /api/config` | Core config |
| `PUT /api/config` | Update core config |
---

View File

@ -143,7 +143,7 @@ Registered by plugins in their `setup()` via `ctx.registerCommand()`:
| `/tunnel` | `@openacp/tunnel` | Manage tunnels |
| `/tunnels` | `@openacp/tunnel` | List active tunnels |
| `/usage` | `@openacp/usage` | View usage and cost |
| `/bypass` | `@openacp/security` | Toggle auto-approve mode |
| `/dangerous` | `@openacp/security` | Toggle auto-approve mode |
---

View File

@ -65,18 +65,14 @@ Wraps an `AgentInstance` with:
- **Prompt queue** -- messages are processed serially, never in parallel
- **Auto-naming** -- after the first prompt, asks the agent to summarize the conversation into a short title
- **Lifecycle management** -- tracks state (idle, processing, waiting_permission, ended)
- **Config options** -- stores agent-declared config options (`ConfigOption[]`) for modes, models, and toggles
- **Agent switch tracking** -- maintains `agentSwitchHistory` with timestamps and prompt counts per agent
```typescript
class Session {
readonly id: string
readonly agentName: string
state: SessionState // 'idle' | 'processing' | 'waiting_permission' | 'ended'
configOptions: ConfigOption[] // agent-declared config (modes, models, etc.)
enqueuePrompt(text: string, attachments?: Attachment[]): Promise<void>
switchAgent(agentName: string): Promise<void>
cancel(reason?: string): Promise<void>
destroy(): Promise<void>
}
@ -84,10 +80,6 @@ class Session {
Sessions emit events through the EventBus that plugins can subscribe to (e.g., `session:afterDestroy` for cleanup).
### Lazy session resume
When a command or message targets a session that has been evicted from memory (e.g., after a server restart), `core.getOrResumeSession()` transparently loads the session record from the store and resumes it. This means commands dispatched to dormant sessions work without the user manually restarting the session.
---
## AgentInstance
@ -281,25 +273,6 @@ The transformer produces `OutgoingMessage` with types: `text`, `thought`, `tool_
---
## InstanceContext
Encapsulates all resolved paths for a single OpenACP instance. Every core module (ConfigManager, SessionStore, AgentStore) receives an `InstanceContext` instead of hardcoding `~/.openacp/`.
```typescript
interface InstanceContext {
id: string
root: string // e.g. ~/.openacp/ or ./my-instance/.openacp/
configPath: string // <root>/config.json
logDir: string // <root>/logs/
pluginDir: string // <root>/plugins/
// ... other resolved paths
}
```
The `InstanceRegistry` at `~/.openacp/instances.json` tracks all instances by ID, enabling `openacp status --all` to show every instance's state. See [Multi-Instance](../features/multi-instance.md) for the user-facing guide.
---
## Adapter Primitives
Shared framework in `src/core/adapter-primitives/` that adapter plugins build on:
@ -310,12 +283,7 @@ Shared framework in `src/core/adapter-primitives/` that adapter plugins build on
- **DraftManager** -- buffers text chunks and sends periodic batch updates
- **SendQueue** -- rate-limited message queue with per-category intervals
- **ToolCallTracker** -- tracks tool calls to enable message editing on status updates
- **ActivityTracker** -- manages thinking indicators and tool state aggregation
- **OutputModeResolver** -- resolves the 3-level cascade (session → adapter → global → default)
- **ToolStateMap** -- accumulates tool events into a unified state for rendering
- **DisplaySpecBuilder** -- builds display specifications per output mode level
- **ThoughtBuffer** -- buffers thinking content for deferred rendering
- **ToolCardState** -- manages debounced tool card updates (batches rapid events)
- **ActivityTracker** -- manages thinking indicators
```
IChannelAdapter (thin interface)

View File

@ -1,8 +1,8 @@
# Writing Your Own Plugin — Full API Reference
# Writing Your Own Plugin
This is the **complete API reference** for building OpenACP plugins. It covers every API surface: services, commands, middleware, events, settings, storage, overrides, and publishing.
This guide walks through building an OpenACP plugin from scratch. By the end, you'll have a working plugin that registers services, commands, and middleware.
> **New to plugin development?** Start with [Getting Started: Your First Plugin](../extending/getting-started-plugin.md) — a hands-on tutorial that walks you through scaffolding, developing, testing, and publishing your first plugin. Come back here when you need the full API details.
> **Quick Start**: Want to get up and running fast? See [Getting Started: Your First Plugin](../extending/getting-started-plugin.md) for a step-by-step tutorial using the scaffold generator and dev mode. Then come back here for the full API reference.
>
> **Plugin SDK**: For type exports, base classes, and testing utilities, see the [Plugin SDK Reference](../extending/plugin-sdk-reference.md).
>

View File

@ -1,13 +1,10 @@
# Extending OpenACP
OpenACP is designed to be extended. You can build plugins that add new features, create custom channel adapters that connect OpenACP to any messaging platform, and contribute improvements back to the core project.
OpenACP is designed to be extended. You can build custom channel adapters that connect OpenACP to any messaging platform, package and distribute those adapters as npm plugins, and contribute improvements back to the core project.
## In this section
This section covers everything you need to go from zero to a published adapter:
- [**Getting Started: Your First Plugin**](getting-started-plugin.md) — Step-by-step tutorial: scaffold, develop, test, and publish a plugin from scratch.
- [**Plugin System**](plugin-system.md) — Installing, listing, configuring, and uninstalling plugins via the CLI.
- [**Plugin SDK Reference**](plugin-sdk-reference.md) — Types, base classes, adapter primitives, and testing utilities provided by `@openacp/plugin-sdk`.
- [**Dev Mode**](dev-mode.md) — Hot-reload development workflow for plugin authors.
- [**Building Adapters**](building-adapters.md) — Step-by-step guide to implementing a `ChannelAdapter` for a new messaging platform.
- [**Adapter Reference**](adapter-reference.md) — Full method signatures, type definitions, and lifecycle documentation for adapters.
- [**Contributing**](contributing.md) — Dev setup, testing conventions, PR process, and publishing plugins to the registry.
- [Plugin System](plugin-system.md) — Installing, listing, and uninstalling plugins via the CLI.
- [Building Adapters](building-adapters.md) — Step-by-step guide to implementing a `ChannelAdapter`.
- [Adapter Reference](adapter-reference.md) — Full method signatures, type definitions, and lifecycle documentation.
- [Contributing](contributing.md) — Dev setup, testing conventions, and PR process.

View File

@ -1,8 +1,6 @@
# Getting Started: Your First Plugin
This is a **hands-on tutorial** that walks you through creating, developing, testing, and publishing an OpenACP plugin from scratch. No prior knowledge of OpenACP internals is required.
> **Looking for the full API reference?** See [Writing Plugins — Full API Reference](../architecture/writing-plugins.md) for every API surface including services, middleware, events, settings, storage, and overrides.
This tutorial walks you through creating, developing, testing, and publishing an OpenACP plugin from scratch. No prior knowledge of OpenACP internals is required.
---
@ -79,7 +77,7 @@ hello-world/
The scaffold generates two documentation files to help you (and your tools) work with the plugin:
- **CLAUDE.md** — A comprehensive technical reference for AI coding agents. Contains the full plugin API, all 19 middleware hooks, permissions, testing utilities, and code patterns. An agent with zero prior context can read this file and write a complete plugin.
- **CLAUDE.md** — A comprehensive technical reference for AI coding agents. Contains the full plugin API, all 18 middleware hooks, permissions, testing utilities, and code patterns. An agent with zero prior context can read this file and write a complete plugin.
- **PLUGIN_GUIDE.md** — A shorter, practical guide for human developers. Covers the development workflow, code examples for common tasks (commands, services, middleware, settings), testing, and publishing.
### package.json

View File

@ -1,6 +1,6 @@
# Plugin System Overview
# Plugin System
> **Note:** This page provides a quick overview of plugin management from a user's perspective. For the full technical deep dive into the plugin infrastructure, see [Architecture > Plugin System](../architecture/plugin-system.md).
> **Note:** OpenACP has been refactored to a microkernel plugin architecture. This page provides a quick overview. For the full guide, see [Architecture > Plugin System](../architecture/plugin-system.md).
---
@ -21,7 +21,7 @@ Plugins can:
## Installing a Plugin
```bash
openacp plugin install @community/my-plugin
openacp plugins install @community/my-plugin
```
If the plugin has `essential: true`, its interactive `install()` hook runs immediately. Otherwise, it's registered and available on next restart.
@ -37,7 +37,7 @@ Shows all installed plugins with their version, source (builtin/npm), and enable
## Configuring a Plugin
```bash
openacp plugin configure @community/my-plugin
openacp plugins configure @community/my-plugin
```
Runs the plugin's interactive `configure()` hook.
@ -45,8 +45,8 @@ Runs the plugin's interactive `configure()` hook.
## Disabling / Enabling
```bash
openacp plugin disable @openacp/speech
openacp plugin enable @openacp/speech
openacp plugins disable @openacp/speech
openacp plugins enable @openacp/speech
```
Built-in plugins cannot be uninstalled, but they can be disabled.
@ -54,8 +54,8 @@ Built-in plugins cannot be uninstalled, but they can be disabled.
## Uninstalling
```bash
openacp plugin uninstall @community/my-plugin
openacp plugin uninstall @community/my-plugin --purge # also delete settings
openacp plugins uninstall @community/my-plugin
openacp plugins uninstall @community/my-plugin --purge # also delete settings
```
---

View File

@ -5,13 +5,9 @@ OpenACP comes with powerful features beyond basic chat. These capabilities let y
## What's in this section
- [**Tunneling**](tunnel.md) — Expose local ports to the internet via Cloudflare, ngrok, bore, or Tailscale, with a built-in file viewer for code and diffs.
- [**Context & Resume**](context-resume.md) — Resume sessions with full conversation history from previous agent runs, with built-in history recording and Entire.io checkpoint support.
- [**Output Modes**](output-modes.md) — Choose how much detail you see when your agent is working: just the result, the highlights, or everything.
- [**Context & Resume**](context-resume.md) — Resume sessions with full conversation history from previous agent runs, powered by Entire.io checkpoints.
- [**Usage & Budget**](usage-and-budget.md) — Track token consumption and API costs per session, with configurable monthly budget warnings.
- [**Session Persistence**](session-persistence.md) — Sessions survive daemon restarts; resume exactly where you left off.
- [**Session Handoff**](session-handoff.md) — Transfer a running session from your terminal into Telegram or Discord (and back).
- [**Agent Switch**](agent-switch.md) — Switch between AI agents mid-conversation while preserving context.
- [**Workspaces**](multi-instance.md) — Run separate OpenACP environments for different projects, teams, or use cases.
- [**App Connectivity**](app-connectivity.md) — Connect desktop and web apps to OpenACP via local discovery or remote tunnel links.
- [**Doctor**](doctor.md) — Run a full system health check with `openacp doctor` to catch misconfigurations before they cause problems.
- [**Assistant Mode**](assistant-mode.md) — A dedicated Assistant topic in Telegram that manages your sessions, agents, and settings through natural language.

View File

@ -1,103 +0,0 @@
# Agent Switch
## What it is
Agent switch lets you change which AI agent is handling your session mid-conversation, without losing context. You start a conversation with one agent, then switch to another — the new agent receives the full conversation history and picks up where the previous one left off.
The thread or topic in your messaging platform stays the same. Only the agent handling the conversation changes.
---
## Use cases
- You are using Claude Code for a task and want to compare how Gemini CLI approaches the same problem.
- Your current agent is slow or hitting rate limits and you want to temporarily switch to another.
- You want to use a specialized agent for a sub-task, then return to your primary agent.
---
## Usage
Run `/switch` inside an existing session topic or thread:
```
/switch # show a menu of available agents
/switch claude # switch directly to the claude agent
/switch gemini # switch directly to the gemini agent
```
When you run `/switch <agent>`, OpenACP:
1. Collects the conversation history from the current session.
2. Starts a new session with the target agent (or resumes an existing one — see below).
3. Injects the conversation history into the new agent as context.
4. Routes all subsequent messages to the new agent.
---
## Session resume
If you switch back to an agent you used earlier in the same thread, and no new user prompts were sent since you last left that agent, OpenACP will attempt to resume the old session rather than creating a new one. This avoids redundant context injection and preserves any in-progress agent state.
Resume only applies when the agent supports it via ACP. If the agent does not support resume, a new session is always created with history injected.
---
## History labels
When conversation history is injected into the new agent, OpenACP can prefix each assistant message with the name of the agent that produced it. This helps the incoming agent distinguish between its own prior responses and those from a different model.
Labels are enabled by default. To toggle:
```
/switch label on # enable agent name labels (default)
/switch label off # disable agent name labels
```
This setting is also controlled by the `agentSwitch.labelHistory` config option:
```json
{
"agentSwitch": {
"labelHistory": true
}
}
```
With labels enabled, injected history looks like:
```
[claude] Here is the refactored function...
[gemini] I would approach it differently...
```
With labels disabled, the history is injected as-is without any prefixes.
---
## Configuration
| Field | Type | Default | Description |
|---|---|---|---|
| `agentSwitch.labelHistory` | boolean | `true` | Prefix assistant messages in injected history with the agent name |
Configure via `~/.openacp/config.json` or the `/settings` command.
---
## Platform support
| Platform | Supported |
|---|---|
| Telegram | Yes |
| Discord | Yes |
| Slack | Yes |
---
## Notes
- Only agents that are installed and ready can be switched to. Use `/agents` to check what is installed.
- The original session thread or topic is preserved across all switches.
- Switching does not cancel an in-progress prompt. If the current agent is actively running, cancel it first with `/cancel` before switching.
- When a switch is in progress, OpenACP emits a "Switching from A to B..." system message and `session:agentSwitch` events (`starting` / `succeeded` / `failed`) so UIs can show loading and error states while the switch is running.

View File

@ -1,52 +0,0 @@
# App Connectivity
## What it is
App connectivity lets desktop and web clients connect to a running OpenACP instance — both on the same machine and remotely (via tunnel). This enables GUI apps, web dashboards, and mobile clients to interact with your OpenACP server.
---
## Connecting from the same machine
Apps running on the same machine can discover and connect to OpenACP automatically. No setup is needed — the app reads credentials from a local file that only your user account can access.
---
## Connecting remotely (phone, another computer)
For remote connections, run:
```bash
openacp remote
```
This displays:
- **Local URL** — for same-machine access
- **Tunnel URL** — public HTTPS URL via your configured tunnel provider
- **QR code** — scan from your phone to connect instantly
Each link contains a **one-time access code** that expires after 30 minutes. This means:
- The link only works once — sharing it twice does not work
- No long-lived secrets appear in browser history or chat logs
- The code is exchanged for a secure token on first use
If `tunnel.enabled` is `true` in your config, the tunnel starts automatically and `openacp remote` uses the existing tunnel URL.
---
## Connection methods
| Method | Best for | How it works |
|--------|----------|--------------|
| Local auto-discovery | Desktop apps on the same machine | App reads credentials from a local file |
| `openacp remote` link | Sharing with your phone or a teammate | One-time code, exchanged for a secure token |
| QR code | Quick mobile app setup | Same as remote link, but you scan instead of copy-paste |
---
## Technical details
- Local discovery uses the instance registry at `~/.openacp/instances.json`. The API port is read from `<instance-root>/api.port` and authentication uses `<instance-root>/api-secret` directly.
- Remote access codes are generated via `POST /api/v1/auth/codes` and exchanged for JWT tokens via `POST /api/v1/auth/exchange`. JWTs can be refreshed within a 7-day window.
- See [Security](../self-hosting/security.md) for details on roles, scopes, and token management.

View File

@ -10,32 +10,38 @@ This lets you continue work naturally. The agent knows the history without you h
## How it works
When you resume a session, OpenACP collects conversation history from your previous sessions — what you asked, what the agent did, and which files were changed. This history is formatted as a summary and injected into the new session so the agent has full context.
The `ContextManager` maintains a list of registered context providers. When a session resumes, OpenACP queries the appropriate provider for the relevant history, receives a formatted markdown document, and prepends it to the first prompt.
OpenACP automatically records conversation history for every session. It captures your prompts, the agent's responses, tool calls, file edits, and permission decisions. History is stored locally in `~/.openacp/history/`, one file per session.
Providers are pluggable. The current built-in provider is `EntireProvider`, which reads conversation history stored by the [Entire.io](https://entire.io) git checkpoint system.
When multiple past sessions are relevant, history is merged chronologically. OpenACP automatically adjusts the level of detail based on how many sessions are included — recent sessions get full detail, older ones get shorter summaries. If the combined history is too large, the oldest sessions are trimmed first.
### Entire.io support
OpenACP can also read conversation history from [Entire.io](https://entire.io) git checkpoints. This is used as a fallback when local history is not available.
Results are cached on disk at `~/.openacp/cache/entire/` so that repeated requests for the same query (same branch, same commit range) do not re-read and re-parse transcript files.
---
## Technical details
## Entire.io provider
Under the hood, the `ContextManager` maintains a list of registered context providers. Two are built in:
Entire.io saves git checkpoints during agent sessions. Each checkpoint stores:
- **HistoryProvider** — records conversation history directly within OpenACP via middleware hooks (`agent:beforePrompt`, `agent:afterEvent`, `permission:afterResolve`).
- **EntireProvider** — reads conversation history from Entire.io git checkpoints.
- The agent name and git branch
- A JSONL transcript of the conversation (user messages and assistant responses, including file edits and writes)
- The list of files touched
Results are cached on disk at `~/.openacp/cache/entire/` so that repeated requests for the same query do not re-read and re-parse transcript files. Providers are pluggable — plugins can register custom context providers.
The `EntireProvider` is available when the repository contains an `entire` git branch. It supports several query types for resolving which sessions to include:
| Query type | Example | Description |
|------------|---------|-------------|
| `branch` | `main` | All sessions on a specific branch |
| `commit` | `abc12345` | Sessions associated with a specific commit |
| `pr` | `https://github.com/.../pull/42` | Sessions for a pull request |
| `checkpoint` | `chk_abc123` | A single specific checkpoint |
| `session` | `sess_abc123` | A single session by ID |
| `latest` | `5` | The N most recent sessions (default 5) |
---
## Adaptive rendering modes
Conversation history can be long. To avoid consuming the entire context window, OpenACP automatically selects a rendering mode based on how many conversation turns are included:
Conversation history can be long. To avoid consuming the entire context window, the provider automatically selects a rendering mode based on total turn count:
| Mode | Turns | What is included |
|------|-------|-----------------|
@ -43,9 +49,9 @@ Conversation history can be long. To avoid consuming the entire context window,
| `balanced` | 11 to 25 | User messages in full; diffs truncated to 12 lines; file writes truncated to 15 lines |
| `compact` | more than 25 | User messages in full; edits shown as a one-line summary with line counts; writes shown as filename and line count only |
If the history is still too large after switching to `compact` mode, the oldest sessions are dropped until it fits.
If the resulting markdown still exceeds the configured `maxTokens` limit, the provider automatically downgrades to `compact` mode. If it is still too large, the oldest sessions are dropped until it fits.
A note is always appended reminding the agent that the history may be outdated and should not be taken as ground truth for current file contents.
A disclaimer is always appended to the context document reminding the agent that the history may be outdated and should not be taken as ground truth for current file contents.
---

View File

@ -1,94 +0,0 @@
# Workspaces
## What are workspaces?
When you first set up OpenACP, everything lives in one place: your bot tokens, agent settings, session history, and logs. This is your **main workspace** — it works great for most people.
But sometimes you need separate environments. Maybe you want:
- A **work** setup with one Telegram group and budget limits, and a **personal** setup with a different group and no limits.
- A **project-specific** setup that uses a different default agent or different permissions.
- A **testing** setup where you try out new plugins without breaking your main bot.
Workspaces let you run completely independent OpenACP setups on the same machine. Each workspace has its own settings, sessions, and data — they do not interfere with each other.
---
## Your main workspace
By default, OpenACP stores everything in a hidden folder called `~/.openacp/`. This is your main (global) workspace. When you run `openacp start` or any other command, this is the workspace that gets used.
You do not need to do anything special to use the main workspace. It is set up automatically the first time you run OpenACP.
---
## Creating a project workspace
If you want a separate workspace for a specific project, navigate to that project's folder and create a local workspace:
```bash
cd ~/my-project
openacp start --local
```
OpenACP creates a `.openacp/` folder inside your project directory and launches the setup wizard. From now on, whenever you run `openacp` from inside `~/my-project`, it automatically uses this project workspace instead of the main one.
You can also copy settings from your main workspace so you do not have to set up everything from scratch:
```bash
cd ~/my-project
openacp start --local --from ~/.openacp
```
This copies your existing settings but asks you to confirm sensitive values like bot tokens (since a different Telegram group or Discord server might be needed).
---
## Switching between workspaces
OpenACP automatically picks the right workspace based on where you run the command:
- **Inside a project folder** with `.openacp/` — uses the project workspace.
- **Anywhere else** — uses your main workspace.
If you want to be explicit:
```bash
openacp start --local # force the project workspace (current folder)
openacp start --global # force the main workspace
```
---
## Seeing all your workspaces
To check which workspaces exist and whether they are running:
```bash
openacp status --all
```
This shows every workspace with its name, location, and whether a bot is currently running.
---
## How workspaces stay separate
Each workspace runs independently:
- **Separate settings** — each workspace has its own `config.json`. Changing the agent in one workspace does not affect the other.
- **Separate sessions** — conversations in the work workspace are not visible in the personal workspace.
- **Separate bots** — each workspace can connect to a different Telegram group or Discord server, or even use different bot tokens entirely.
- **Separate ports** — if both workspaces are running simultaneously, they automatically use different network ports so there are no conflicts.
---
## When do you need multiple workspaces?
Most users only need the main workspace. Consider adding a project workspace when:
- You want a **completely different bot configuration** for a project (different group, different agents, different budget).
- You are **developing or testing plugins** and do not want to risk your main setup.
- You manage **multiple teams** that each need their own isolated OpenACP environment.
If you just want to switch between different agents or projects within the same bot, you do not need a new workspace — use sessions and the `/new` command instead.

View File

@ -1,117 +0,0 @@
# Output Modes
## What are output modes?
When your AI agent works on a task, it does many things behind the scenes: reading files, editing code, running commands, thinking through problems. Output modes let you choose **how much of that activity you want to see** in your chat.
Think of it like a camera zoom:
- **Zoomed out** (`low`) — you see the big picture only. The agent is working, and you will see the final result.
- **Normal view** (`medium`) — you see what the agent is doing at a glance: which files it is reading, what commands it is running, and short summaries of the results.
- **Zoomed in** (`high`) — you see everything: the agent's reasoning, full command output, complete file diffs, and detailed progress.
---
## The three modes
### Low — "Just tell me when it is done"
Best for: non-technical users, managers, or when you are on mobile and do not want chat noise.
What you see:
- A compact row of small icons showing the types of tools the agent is using (file, terminal, search, etc.)
- The agent's final text response
What you do not see:
- File names and contents
- Command output
- The agent's thinking process
### Medium — "Show me the highlights" (default)
Best for: most users, day-to-day coding.
What you see:
- Tool names and short descriptions ("Editing `src/app.ts`", "Running `npm test`")
- File names involved in each operation
- Short summaries of command output
- The agent's final text response
What you do not see:
- Full command output (available via viewer links when output is large)
- The agent's internal reasoning
### High — "Show me everything"
Best for: developers debugging issues, reviewing agent work in detail, or when you want to understand exactly what the agent is doing.
What you see:
- Everything from medium mode, plus:
- Full command output inline
- The agent's thinking/reasoning process
- Complete code diffs
- Detailed plan steps
- Links to the viewer for very large output
---
## Changing the output mode
### Quick change in chat
Type this in any chat where OpenACP is active:
```
/outputmode low
/outputmode medium
/outputmode high
```
This changes the default for all sessions on that platform (Telegram, Discord, or Slack).
To change it for **just the current session** (without affecting other sessions):
```
/outputmode session low
/outputmode session high
```
To go back to the default:
```
/outputmode reset # reset the platform default
/outputmode session reset # reset this session's override
```
### On Discord
While the agent is working, buttons appear below the activity card: **Low**, **Medium**, **High**. Tap one to switch instantly — no command needed.
### On Slack
Type `/outputmode` to open a settings panel where you can pick a mode with radio buttons and choose whether the change applies to just this session or all sessions.
---
## How defaults work
Output mode follows a simple priority rule — the most specific setting wins:
1. **This session** — if you set `/outputmode session high`, this session shows full detail.
2. **This platform** — if you set `/outputmode low` in Telegram, all Telegram sessions default to low (unless a session has its own override).
3. **Global default** — the fallback when nothing else is set. Default is `medium`.
**Example**: You set Telegram to `low` because you check it on your phone. Discord stays at `medium`. But for one tricky debugging session in Telegram, you set `/outputmode session high` to see everything. That session shows full detail while all other Telegram sessions stay quiet.
---
## Which mode should I use?
| Situation | Recommended mode |
|-----------|-----------------|
| Checking progress on your phone | `low` |
| Normal coding sessions | `medium` |
| Debugging why something failed | `high` |
| Sharing your screen with a non-technical audience | `low` |
| Reviewing what the agent changed before merging | `high` |
| Running many sessions simultaneously | `low` or `medium` |

View File

@ -12,7 +12,7 @@ No state is lost. The agent process keeps running; only the "owner" of the sessi
A typical flow:
1. You are working at your desk with Claude Code or OpenCode open in the terminal.
1. You are working at your desk with Claude Code open in the terminal.
2. You need to step away but want to keep supervising the agent.
3. You run `openacp integrate` (or trigger the `/openacp:handoff` slash command from inside the agent).
4. The session appears as a new topic in your Telegram group or Discord server.
@ -20,62 +20,61 @@ A typical flow:
---
## How to set up handoff
## How it works
### Step 1: Install the integration
Handoff relies on two components installed by `openacp integrate`:
Run the integrate command and follow the prompts:
### 1. Inject hook (`openacp-inject-session.sh`)
This shell script runs as an agent hook (e.g. on every new conversation turn for Claude Code). It reads the agent's session ID and working directory from the hook payload and injects them as context variables so the agent is always aware of its own ACP session ID.
### 2. Handoff script (`openacp-handoff.sh`)
This script calls `openacp adopt <agent> <session_id>` to register the terminal session with the running OpenACP daemon, making it visible in the messaging platform.
```bash
# Manually trigger a handoff
openacp-handoff.sh <session_id> [working_directory] [channel]
```
### 3. Slash command / skill
`openacp integrate` also installs a slash command (for Claude Code: `/openacp:handoff`) that instructs the agent to run the handoff script automatically:
```
/openacp:handoff # hand off to the default adapter
/openacp:handoff telegram # hand off specifically to Telegram
/openacp:handoff discord # hand off to Discord
```
---
## Installation
Run the integrate command to install hooks for a supported agent:
```bash
openacp integrate
```
You will be asked which agent to integrate (Claude Code, OpenCode, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). The command installs the needed integration so your agent can hand off sessions to OpenACP.
This is interactive and asks which agent to integrate (Claude Code, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). It installs scripts to the agent's hooks directory and adds an entry to the agent's settings file.
To uninstall later:
To uninstall:
```bash
openacp integrate --uninstall
```
### Step 2: Use the handoff command
Once integrated, you can hand off any session from your terminal to your messaging app:
```
/openacp:handoff # hand off to the default platform
/openacp:handoff telegram # hand off specifically to Telegram
/openacp:handoff discord # hand off to Discord
```
The session appears as a new topic in your Telegram group or Discord server. You can continue sending prompts and approving permission requests from your phone.
---
## Requirements
- The OpenACP daemon must be running (`openacp start`) on the same machine as the terminal agent.
- At least one messaging adapter (Telegram, Discord, or Slack) must be configured and connected.
- `jq` is required only for hook-based integrations (Claude/Cursor/Gemini/Cline). OpenCode plugin integration does not require `jq`.
- The OpenACP daemon must be running in daemon mode (`openacp start --daemon`) on the same machine as the terminal agent.
- The daemon must have at least one messaging adapter (Telegram or Discord) configured and connected.
- `jq` must be installed on the machine (`brew install jq` on macOS, `apt install jq` on Linux). The inject hook uses `jq` to parse the agent's hook payload.
---
## Supported agents
Currently supported agents include Claude Code, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, OpenAI Codex, and others. Run `openacp integrate --list` to see the full list.
---
## Technical details
Most handoff integrations rely on two shell scripts installed by `openacp integrate`:
- **Inject hook** (`openacp-inject-session.sh`) — runs as an agent hook on every conversation turn, reads the agent's session ID from the hook payload, and injects it as a context variable.
- **Handoff script** (`openacp-handoff.sh`) — calls `openacp adopt <agent> <session_id>` to register the terminal session with the running OpenACP daemon, making it visible in the messaging platform.
For OpenCode, handoff is installed via a command + plugin pair under `~/.config/opencode/`:
- **Command** (`commands/openacp-handoff.md`) — provides `/openacp:handoff`.
- **Plugin** (`plugins/openacp-handoff.js`) — injects current OpenCode session ID so the command can call `openacp adopt opencode <session_id>`.
If OpenCode is started with `--pure`, plugins are disabled and session ID injection is unavailable. In this mode, `/openacp:handoff` is not supported.
`openacp integrate` supports agents that expose a hook system for injecting context into every session. Currently supported agents include Claude Code, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, OpenAI Codex, and others. Run `openacp integrate --list` to see the full list.

View File

@ -2,51 +2,77 @@
## Sessions survive restarts
When you stop and restart OpenACP, your sessions are not lost. OpenACP saves session records to disk as they are created and updated, so everything — session names, which agent was running, which Telegram topic or Discord thread they belonged to — is restored automatically on restart.
By default, stopping and restarting the OpenACP daemon would lose track of all active sessions — their IDs, which agent was running, which Telegram topic or Discord thread they were attached to. Session persistence solves this by writing session records to disk as they are created and updated.
You can continue sending messages to an existing session topic after a restart. OpenACP reconnects to the agent process if it is still alive, or starts a new agent session linked to the same topic.
When the daemon restarts, it reloads all stored records. Sessions that were active before the restart are shown in their previous state. You can resume sending prompts to an agent session that survived a restart as long as the underlying agent process is still alive or can be reconnected.
---
## What happens after a restart
## Storage location
1. OpenACP reloads all saved sessions and restores them in your messaging app.
2. Sessions that were active before the restart appear in their previous state.
3. Sending a new message in an existing session topic reconnects to the agent automatically.
4. If the agent process did not survive the restart, the session shows an error notification. You can create a new session or use `/resume` to continue with history attached.
---
## Automatic cleanup
Old session records are cleaned up automatically. By default, sessions that have not been active for **30 days** are removed. Active sessions are never cleaned up regardless of age.
You can configure the retention period in `~/.openacp/config.json`:
Session records are stored in `~/.openacp/sessions.json`. The file format is:
```json
{
"sessionStore": {
"ttlDays": 30
"version": 1,
"sessions": {
"<sessionId>": { ... }
}
}
```
Writes are debounced (2-second delay) to avoid excessive disk I/O during rapid session updates. The file is flushed synchronously on `SIGTERM`, `SIGINT`, and process exit.
If the file is unreadable on startup (corrupt JSON, wrong version), OpenACP logs the error and starts with an empty session map rather than crashing.
---
## Technical details
## What is persisted
Session records are stored in `~/.openacp/sessions.json`. Each record stores:
Each session record stores:
| Field | Description |
|-------|-------------|
| `sessionId` | Unique OpenACP session ID |
| `agentSessionId` | ID assigned by the agent subprocess |
| `agentSessionId` | ID assigned by the agent subprocess (ACP session ID) |
| `originalAgentSessionId` | Agent session ID before the most recent handoff or restore |
| `channelId` | Which adapter owns this session (`telegram`, `discord`, etc.) |
| `agentName` | Name of the agent (e.g. `claude`, `gemini`) |
| `workingDirectory` | Filesystem path the agent is working in |
| `status` | `initializing`, `active`, `idle`, `finished`, `error` |
| `name` | Display name auto-assigned after the first prompt |
| `threadId` | Platform thread or topic ID |
| `createdAt` / `lastActiveAt` | Timestamps for session lifecycle |
| `threadId` | Platform thread or topic ID (e.g. Telegram forum topic ID) |
| `platform` | Adapter-specific metadata (e.g. Telegram chat ID) |
| `createdAt` | ISO timestamp when the session was created |
| `lastActiveAt` | ISO timestamp of the most recent activity |
Writes are debounced to avoid excessive disk I/O. The file is flushed on process exit to prevent data loss. If the file is unreadable on startup, OpenACP logs the error and starts with an empty session map rather than crashing.
---
## TTL cleanup
Old session records are pruned automatically. By default, records that have not been active for **30 days** are removed. Active and initializing sessions are never pruned regardless of age.
Configure the TTL in `~/.openacp/config.json`:
```json
{
"sessions": {
"ttlDays": 30
}
}
```
Cleanup runs on startup and then every 24 hours for long-running instances.
---
## Resuming after a restart
After restarting the daemon:
1. OpenACP reloads `sessions.json` and restores all session records.
2. Adapter-specific state (e.g. Telegram topic IDs) is re-associated from the `platform` metadata.
3. Sessions that were `active` or `initializing` before the restart are visible again in your messaging app.
4. Sending a new message to an existing session topic reconnects to the agent process or creates a new agent session linked to the same record.
If the agent process did not survive the restart, the session transitions to `error` state and you will see an error notification in the topic. Create a new session or use `/resume` to continue work in a fresh session with history attached.

View File

@ -43,8 +43,13 @@ Add a `tunnel` block to `~/.openacp/config.json` (see [Configuration](../self-ho
"tunnel": {
"enabled": true,
"provider": "cloudflare",
"port": 7080,
"maxUserTunnels": 5,
"storeTtlMinutes": 60,
"auth": {
"enabled": false,
"token": ""
},
"options": {}
}
}
@ -52,10 +57,12 @@ Add a `tunnel` block to `~/.openacp/config.json` (see [Configuration](../self-ho
| Field | Default | Description |
|-------|---------|-------------|
| `enabled` | `false` | Enable or disable the tunnel feature. When `true`, the tunnel auto-starts on server boot. |
| `enabled` | `false` | Enable or disable the tunnel feature |
| `provider` | `"cloudflare"` | One of `cloudflare`, `ngrok`, `bore`, `tailscale` |
| `port` | `7080` | Local port for the internal file viewer server. Auto-increments if in use. |
| `maxUserTunnels` | `5` | Maximum number of simultaneous user-created tunnels |
| `storeTtlMinutes` | `60` | How long file/diff viewer entries are kept in memory |
| `auth.enabled` | `false` | Require a bearer token to access the file viewer |
| `options` | `{}` | Provider-specific options (see below) |
### Provider-specific options
@ -106,24 +113,24 @@ Inside Telegram or Discord, if you have the agent integration installed, the age
## File viewer
When an agent reads, edits, or writes a file, OpenACP can generate a clickable link that opens the content in a web-based viewer with syntax highlighting and side-by-side diff view. This is especially useful when reviewing changes from your phone.
The file viewer is an internal HTTP server that OpenACP starts alongside the tunnel. When an agent reads, edits, or writes a file, it can register that file or diff in the viewer and send you a clickable link.
The viewer supports dozens of languages including TypeScript, JavaScript, Python, Rust, Go, Java, and many more. Large tool output that does not fit inline in chat is also viewable through these links.
- **File view** — renders file content with Monaco editor syntax highlighting. Supported languages include TypeScript, JavaScript, Python, Rust, Go, Java, Kotlin, Ruby, PHP, C/C++, C#, Swift, Bash, JSON, YAML, TOML, XML, HTML, CSS, SCSS, SQL, Markdown, Dockerfile, HCL, Vue, and Svelte.
- **Diff view** — renders a side-by-side diff of old vs. new content.
Viewer links expire automatically after the configured `storeTtlMinutes` (default 60 minutes).
The viewer enforces a 1 MB per-entry size limit and rejects file paths that fall outside the session's working directory (path traversal protection). Entries expire automatically after `storeTtlMinutes` (default 60 minutes).
---
## Limits and auto-recovery
## Per-user tunnel limits
- Each user or session can open up to `maxUserTunnels` tunnels simultaneously (default 5).
- When `tunnel.enabled` is `true`, the tunnel starts automatically on server boot — no manual start needed.
- If the tunnel connection drops, OpenACP automatically detects the failure and restarts the tunnel within about 90 seconds.
Each user or session can open up to `maxUserTunnels` tunnels simultaneously (default 5). This prevents runaway tunnel creation. Tunnels created by a session are tracked and can be stopped when the session ends via `stopBySession`.
---
## Security
- Files outside the session's working directory cannot be viewed — path access is restricted to prevent unauthorized file access.
- Viewer entries expire automatically and are cleaned up periodically.
- When connecting apps remotely, `openacp remote` generates a single-use access code instead of embedding secrets in the URL. See [App Connectivity](app-connectivity.md) for details.
- **Auth token**: When `auth.enabled` is true, all requests to the file viewer require a `Bearer <token>` header. Set `auth.token` to a secret value.
- **Path validation**: The viewer validates every file path against the session's `workingDirectory`. Files outside that directory are rejected.
- **TTL**: Viewer entries expire after `storeTtlMinutes`. Expired entries are cleaned up every 5 minutes.
- **Tunnel timeouts**: If a provider process does not establish a tunnel within 30 seconds, it is killed and an error is returned.

View File

@ -17,6 +17,14 @@ Each summary includes total tokens, total cost, number of distinct sessions, and
---
## Storage
Usage data is written to `~/.openacp/usage.json` with a debounce of 2 seconds to avoid hammering disk on rapid completions. The file is flushed synchronously on `SIGTERM`, `SIGINT`, and process exit to prevent data loss.
If the file is corrupt on startup, OpenACP saves a `.bak` backup and starts fresh.
---
## Monthly budget
Set a spending limit in `~/.openacp/config.json`:
@ -58,7 +66,7 @@ Monthly usage: $16.32 / $20.00 (82%)
## Retention
Usage records older than the configured retention period are deleted automatically. The default is **90 days**.
Usage records older than the configured retention period are deleted automatically. The default retention is **90 days**. Cleanup runs on startup and then every 24 hours for long-running daemon instances.
To configure retention:
@ -69,9 +77,3 @@ To configure retention:
}
}
```
---
## Technical details
Usage data is stored in `~/.openacp/usage.json`. Writes are batched to avoid excessive disk I/O. The file is saved on process exit to prevent data loss. If the file is corrupt on startup, OpenACP saves a backup and starts fresh.

View File

@ -190,16 +190,6 @@ Slash commands are registered automatically when OpenACP starts (guild-scoped, s
| `/handoff` | Get a terminal command to resume the session locally |
| `/agents` | Browse available agents |
| `/install <name>` | Install an agent |
| `/outputmode [low\|medium\|high\|reset] [session]` | Set output detail level; use `session` scope to override for the current thread only |
| `/verbosity` | Deprecated alias for `/outputmode` |
| `/bypass` | Toggle auto-approval of all permission requests |
| `/tts [on\|off]` | Toggle text-to-speech for the current session |
| `/settings` | Change configuration in-chat |
| `/doctor` | Run system diagnostics |
| `/integrate` | Manage agent integrations |
| `/restart` | Restart OpenACP |
| `/update` | Update to the latest version |
| `/clear` | Reset the assistant session history |
| `/help` | Show help |
---
@ -209,7 +199,6 @@ Slash commands are registered automatically when OpenACP starts (guild-scoped, s
Each `/new` command creates a **forum thread** in `#openacp-sessions`:
- **Real-time streaming** — agent responses appear as the model generates output, with periodic message edits to minimize Discord API calls.
- **Tool card embeds** — while the agent is working, tool activity is grouped into a single embed with a colored sidebar (🔵 running, 🟢 done, 🔴 error). An action row appears below with `[🔇 Low] [📊 Medium] [🔍 High] [❌ Cancel]` buttons to switch output detail level or abort the session without any slash commands.
- **Auto-naming** — after the first prompt, the thread is renamed to a short summary of the task.
- **File and image support** — attach files, screenshots, or voice messages directly in the thread (up to 25 MB per file).
- **Permission buttons** — when the agent needs approval to run a command or modify a file, **Allow** and **Reject** buttons appear in the thread.

View File

@ -101,29 +101,15 @@ After configuring scopes, subscribe to the message events OpenACP needs to recei
---
## Step 6: Enable Interactivity and Slash Commands
## Step 6: Enable Interactivity
Permission buttons (Allow / Deny) and the `/outputmode` command both require interactivity to be enabled.
### Enable Interactivity
Permission buttons (Allow / Deny) require interactivity to be enabled.
1. In the left sidebar, go to **Interactivity & Shortcuts**.
2. Toggle **Interactivity** to On.
3. In Socket Mode, interactive payloads are delivered over the same WebSocket connection. Leave the **Request URL** field blank or set a placeholder value — it is not used in Socket Mode.
4. Click **Save Changes**.
### Register the `/outputmode` Slash Command
1. In the left sidebar, go to **Slash Commands**.
2. Click **Create New Command**.
3. Fill in the fields:
- **Command**: `/outputmode`
- **Request URL**: leave blank (Socket Mode delivers the payload via WebSocket)
- **Short Description**: `Change output verbosity for this session`
- **Usage Hint**: `[low|medium|high]`
4. Click **Save**.
5. You will be prompted to **Reinstall App** — do this now, or after Step 8 once all config is ready.
---
## Step 7: Get the Signing Secret
@ -143,6 +129,7 @@ Edit `~/.openacp/config.json` and add the Slack section (see the [full configura
"channels": {
"slack": {
"enabled": true,
"adapter": "slack",
"botToken": "xoxb-...",
"appToken": "xapp-1-...",
"signingSecret": "abcd1234efgh5678ijkl9012",
@ -157,13 +144,13 @@ Edit `~/.openacp/config.json` and add the Slack section (see the [full configura
| Field | Description |
|-------|-------------|
| `enabled` | Set to `true` to activate the Slack adapter |
| `adapter` | Must be `"slack"` |
| `botToken` | Bot User OAuth Token from Step 4 (starts with `xoxb-`) |
| `appToken` | App-Level Token from Step 2 (starts with `xapp-1-`) |
| `signingSecret` | Signing Secret from Step 7 |
| `notificationChannelId` | Optional. Slack channel ID for system notifications. Right-click a channel → View Details → copy the ID from the URL (e.g., `C1234567890`) |
| `allowedUserIds` | Optional. Array of Slack user IDs allowed to create sessions. If empty, all workspace members can create sessions. Get a user's ID by opening their profile → click the `•••` menu → **Copy user ID** |
| `channelPrefix` | Prefix for auto-created session channels. Default: `openacp`. Session channels are named `{prefix}-{slug}-{sessionId}` |
| `outputMode` | Optional. Default output verbosity: `"low"`, `"medium"`, or `"high"`. Defaults to `"medium"`. Can be overridden per session with `/outputmode`. See [Output Mode](#output-mode) below |
---
@ -215,7 +202,6 @@ Each OpenACP session in Slack gets its own dedicated channel:
| `/status` | Show current session status or system status |
| `/agents` | List available agents |
| `/help` | Show help |
| `/outputmode [low\|medium\|high]` | Change output verbosity. Omit the argument to open an interactive modal |
### Command Examples
@ -226,52 +212,6 @@ Each OpenACP session in Slack gets its own dedicated channel:
/new → Default agent and default workspace
/newchat → New session using current agent and workspace
/cancel → Cancel the running session
/outputmode high → Switch to High verbosity for this session
/outputmode → Open a modal to choose verbosity and scope
```
---
## Output Mode
The Slack adapter renders agent activity in real time using Slack threads. When the agent starts using tools, a **Processing...** message appears in the channel. Tool details are posted as thread replies. When the response is complete, the message updates to **✅ Done** and the agent's reply appears in the channel.
You can control how much detail is shown with the output mode setting.
### Verbosity Levels
| Mode | What you see |
|------|-------------|
| **Low** 🔇 | A single `🔧 Processing...` → `✅ Done` indicator. No tool details. |
| **Medium** 📊 | Progress indicator with tool names and a running count (`2/5 tools`). Thread shows tool cards with summaries. |
| **High** 🔍 | Full detail: tool input/output, file diffs, viewer links, and the agent's thinking in the thread. |
The default is **Medium**.
### Changing Output Mode
**Inline shortcut** — type directly in a session channel:
```
/outputmode low
/outputmode medium
/outputmode high
```
**Interactive modal** — type `/outputmode` with no arguments to open a modal where you can select the verbosity level and choose whether to apply it to the current session only or to all sessions.
### Setting the Default
To set a default for all sessions, add `outputMode` to your config:
```json
{
"channels": {
"slack": {
"outputMode": "medium"
}
}
}
```
---

View File

@ -1,13 +1,6 @@
# Telegram Setup
This guide walks you through connecting OpenACP to Telegram. OpenACP uses a Telegram group with Topics enabled — each coding session gets its own topic thread for an organized, isolated workspace.
> **Prerequisites:**
> 1. A Telegram group (any size)
> 2. **Topics enabled** — Group Settings → Edit → Topics
> 3. **Bot is admin with "Manage Topics" permission** — Group Settings → Administrators
>
> If these aren't set up when OpenACP first starts, it will send instructions to your group's General topic and keep retrying automatically.
This guide walks you through connecting OpenACP to Telegram. OpenACP uses a Telegram Supergroup with Topics enabled — each coding session gets its own topic thread for an organized, isolated workspace.
## Prerequisites
@ -33,16 +26,16 @@ This guide walks you through connecting OpenACP to Telegram. OpenACP uses a Tele
---
## Step 2: Create a Group with Topics Enabled
## Step 2: Create a Supergroup with Topics Enabled
OpenACP requires a Telegram group with the **Topics** feature enabled. Topics create thread-like channels — one per coding session.
OpenACP requires a Telegram **Supergroup** with the **Topics** feature enabled. Topics create forum-like threads — one per coding session.
1. In Telegram, tap the compose icon and select **New Group**.
2. Add your bot as a member (search for its username).
3. Give the group a name (e.g., `OpenACP`) and create it.
4. Open the group → tap the group name at the top → **Edit** (pencil icon).
5. Scroll down and enable **Topics**.
6. Save the changes.
6. Save the changes. Telegram converts the group to a Supergroup automatically.
---
@ -65,7 +58,7 @@ The bot must be an administrator with the following permissions to manage topics
## Step 4: Get the Chat ID
The Chat ID is the unique numeric identifier for your group. You need it for the config.
The Chat ID is the unique numeric identifier for your Supergroup. You need it for the config.
**Option A: Use the OpenACP setup wizard (recommended)**
@ -117,7 +110,7 @@ Edit `~/.openacp/config.json` and fill in the Telegram section (see the [full co
|-------|-------------|
| `enabled` | Set to `true` to activate the Telegram adapter |
| `botToken` | The token from BotFather (Step 1) |
| `chatId` | The group's Chat ID — negative number starting with `-100` (Step 4) |
| `chatId` | The Supergroup's Chat ID — negative number starting with `-100` (Step 4) |
| `notificationTopicId` | Leave `null` — OpenACP creates this topic on first start |
| `assistantTopicId` | Leave `null` — OpenACP creates this topic on first start |
@ -221,14 +214,13 @@ Environment variables take precedence over values in `config.json`.
- Verify `enabled: true` in the config.
- Check `~/.openacp/logs/` for error messages.
**"Chat must be a group" error**
- Make sure you are using a group (not a channel). Channels are not supported.
**"Chat is not a supergroup" error**
- The group must be a Supergroup. Go to Group Settings and convert it if needed.
- If the group was just created, wait a moment and try again.
**Topics not appearing after first start**
- If OpenACP cannot create topics, it sends a message to the group's General topic with instructions.
- Follow the instructions in that message: enable Topics and/or grant the bot "Manage Topics" permission.
- OpenACP retries automatically every 30 seconds — no need to restart.
**Topics not appearing**
- Topics must be enabled in the group settings before OpenACP starts.
- The bot needs **Manage Topics** admin permission.
**Chat ID is not detected**
- Make sure you sent a message in the group after adding the bot.

View File

@ -18,7 +18,6 @@ openacp stop # Send SIGTERM to the daemon, wait up to 5 s, then SIGKILL
openacp status # Print running/stopped and PID if running
openacp logs # Tail the daemon log file
openacp restart # stop + start
openacp attach # Connect to running daemon: show status + tail logs
```
### `openacp start`
@ -33,10 +32,6 @@ Reads the PID file and sends `SIGTERM`. Polls every 100 ms for up to 5 seconds w
Calling `stop` also removes the running marker file (`~/.openacp/running`), which suppresses autostart on the next boot.
### `openacp restart`
Equivalent to `stop` followed by `start`. If no daemon is running, it skips the stop step and starts a new one. Useful after updating OpenACP to pick up the new version without manually stopping first.
### `openacp status`
Checks whether the PID in the PID file is alive (using `kill -0`). Cleans up stale PID files automatically.
@ -45,33 +40,6 @@ Checks whether the PID in the PID file is alive (using `kill -0`). Cleans up sta
Tails `~/.openacp/logs/openacp.log`. In daemon mode this is where all server output goes.
### `openacp attach`
Connects to a running daemon and shows a rich status display (uptime, active sessions, adapters, tunnel status) followed by live log tailing. Press Ctrl+C to detach without affecting the daemon.
Useful when you want to monitor a daemon that was started earlier or by autostart, without managing it as a foreground process.
## Smart startup
When you run `openacp` (no arguments) and a daemon is already running, instead of printing an error, OpenACP shows a rich status display with an interactive menu:
| Key | Action |
|-----|--------|
| `r` | Restart the daemon |
| `f` | Restart in foreground mode |
| `s` | Show full status details |
| `l` | Tail the log file |
| `q` | Quit |
The display also shows which instance is active (global vs. local) and suggests the local instance when one is available but the global is being used.
You can force a specific mode on startup:
```bash
openacp start --foreground # force foreground regardless of config
openacp start --daemon # force daemon regardless of config
```
## File Locations
| File | Path | Purpose |

View File

@ -11,26 +11,9 @@
No database, no Docker, no external services required beyond the messaging platform bots you configure.
## One-liner install (recommended)
The fastest way to install OpenACP on macOS or Linux:
```bash
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
```
The script automatically:
1. Detects your platform (macOS or Linux).
2. Checks for Node.js 20+ and installs it if missing.
3. Installs `@openacp/cli` globally via npm.
4. Launches the setup wizard.
No prior setup required — the script handles everything.
## Install via npm
If you prefer to manage Node.js yourself, install OpenACP directly from npm:
OpenACP is published as `@openacp/cli` on npm. Install it globally:
```bash
npm install -g @openacp/cli
@ -42,7 +25,7 @@ npm install -g @openacp/cli
openacp --version
```
This prints the installed version (e.g., `2026.401.1`) and exits. If the command is not found, ensure your npm global bin directory is on `PATH`.
This prints the installed version (e.g., `0.6.9`) and exits. If the command is not found, ensure your npm global bin directory is on `PATH`.
## First Run and Setup Wizard

View File

@ -40,22 +40,15 @@ The default of 20 is generous for personal use. Reduce it if you are on a machin
Sessions that have been idle (no new prompt sent) for longer than this value are eligible for automatic cleanup. The default is 60 minutes.
## API Authentication
## API Bearer Token
The REST API uses a two-tier authentication system:
The local REST API (default port `21420`) is protected by a bearer token. The token is stored in:
### Secret token (master key)
The API secret is stored in `<instance-root>/api-secret` (default: `~/.openacp/api-secret`). This file is created automatically on first start with `0600` permissions. The token is a 64-character hex string generated with `crypto.randomBytes(32)`.
The secret token provides full administrative access. Use it for:
- CLI-to-daemon communication (handled automatically).
- Issuing JWT access tokens for apps and integrations.
```http
Authorization: Bearer <contents of api-secret>
```
~/.openacp/api-secret
```
This file is created automatically on first start with `0600` permissions (owner read/write only). The token is a 64-character hex string generated with `crypto.randomBytes(32)`.
At startup, if the file permissions are more permissive than `0600`, a warning is logged:
@ -63,52 +56,17 @@ At startup, if the file permissions are more permissive than `0600`, a warning i
API secret file has insecure permissions (should be 0600). Run: chmod 600 ~/.openacp/api-secret
```
### JWT access tokens
To authenticate API requests, include the token in the `Authorization` header:
For app clients and remote access, OpenACP issues scoped JWT tokens. Unlike the secret token, JWTs are:
- **Scoped** — assigned a role (`admin`, `operator`, or `viewer`) with predefined permissions.
- **Revokable** — can be revoked individually via the API.
- **Time-limited** — expire after a configurable period, with a 7-day refresh window.
- **Stateful** — tracked in `<instance-root>/tokens.json` with last-used timestamps.
#### Roles
| Role | Capabilities |
|------|-------------|
| `admin` | Full access: manage sessions, config, agents, tokens |
| `operator` | Create/manage sessions, send prompts, view config |
| `viewer` | Read-only: view sessions, status, and events |
#### Issuing tokens
Tokens are issued by authenticating with the secret token:
```bash
curl -X POST \
-H "Authorization: Bearer $SECRET" \
-H "Content-Type: application/json" \
-d '{"name": "my-app", "role": "operator"}' \
http://localhost:21420/api/v1/auth/tokens
```http
Authorization: Bearer <contents of ~/.openacp/api-secret>
```
Or use `openacp remote` to generate a one-time access code that can be exchanged for a JWT (see [App Connectivity](../features/app-connectivity.md)).
#### Revoking tokens
```bash
curl -X DELETE \
-H "Authorization: Bearer $SECRET" \
http://localhost:21420/api/v1/auth/tokens/<token-id>
```
### Network security
The CLI reads this file automatically when talking to a running daemon, so you do not need to manage it manually for normal use.
Do not expose the API port externally. The default `host: "127.0.0.1"` binding ensures the API is only reachable from localhost. If you change `api.host` to `0.0.0.0`, the server logs a warning — ensure your firewall blocks external access to port `21420`.
For remote access, use a tunnel instead of exposing the port directly. The tunnel provides HTTPS encryption and access control via one-time codes.
## Bypass Permissions
## Dangerous Mode
Some agent operations (file writes, command execution) require explicit user approval via permission request buttons in the chat. This is the default behavior. For details on how permissions work from a user's perspective, see [Permissions](../using-openacp/permissions.md).
@ -120,12 +78,10 @@ If an agent is configured to run without permission prompts (agent-side configur
2. **Keep `api-secret` at `0600`**. The CLI warns you if it is not. Run `chmod 600 ~/.openacp/api-secret` if needed.
3. **Do not change `api.host` to `0.0.0.0`** unless you have a specific need and have locked down port `21420` with firewall rules. Use tunnels for remote access instead.
3. **Do not change `api.host` to `0.0.0.0`** unless you have a specific need and have locked down port `21420` with firewall rules.
4. **Review `maxConcurrentSessions`** if you share the bot with multiple users. A session per user is reasonable; 20 concurrent ACP agent subprocesses can be resource-intensive.
5. **Rotate the API secret** by deleting `~/.openacp/api-secret` and restarting the daemon. A new token is generated automatically. All existing JWT tokens issued from the old secret become invalid.
5. **Rotate the API secret** by deleting `~/.openacp/api-secret` and restarting the daemon. A new token is generated automatically.
6. **Use daemon mode with autostart** for persistent deployments so the server does not silently go offline after a reboot.
7. **Revoke unused JWT tokens** periodically. Use `GET /api/v1/auth/tokens` to list active tokens and their last-used timestamps. Revoke any you no longer need.

View File

@ -6,12 +6,12 @@
openacp --version
```
This prints the version from the installed package (e.g., `2026.401.1`). The version is read from `package.json` bundled with the binary.
This prints the version from the installed package (e.g., `0.6.9`). The version is read from `package.json` bundled with the binary.
OpenACP also checks for updates automatically at startup. If a newer version is available on npm, you are prompted:
```
Update available: 2026.327.1 → 2026.401.1
Update available: v0.6.7 → v0.6.9
? Update now before starting?
```
@ -26,7 +26,7 @@ npm update -g @openacp/cli
Or to pin to a specific version:
```bash
npm install -g @openacp/cli@2026.401.1
npm install -g @openacp/cli@0.6.9
```
If you are running from source, pull and rebuild:

View File

@ -26,7 +26,7 @@ If you haven't finished initial setup, see the [Slack Setup guide](../platform-s
**Cause:** The Slack event router only processes messages in channels that have an active OpenACP session. Messages in other channels, DMs, or the notification channel are not routed to an agent.
**Solution:**
1. Use `/new` to create a new session — this creates a dedicated channel for the conversation.
1. Use `/openacp-new` to create a new session — this creates a dedicated channel for the conversation.
2. Ensure Socket Mode is enabled for your app: Settings → **Socket Mode → Enable Socket Mode**.
3. Check that the `message.channels` event subscription is present under **Event Subscriptions → Subscribe to bot events**.
4. Verify `security.allowedUserIds` — if non-empty, your Slack user ID must be listed.
@ -55,7 +55,7 @@ If you haven't finished initial setup, see the [Slack Setup guide](../platform-s
**Solution:**
- OpenACP's `SlackSendQueue` serialises outbound API calls automatically to respect rate limits.
- If you hit limits consistently, reduce `security.maxConcurrentSessions` in config.
- Avoid bursting many messages at once; consider using `outputMode: "low"` in your config, or type `/outputmode low` in a session channel to reduce intermediate streaming updates.
- Avoid bursting many messages at once; consider using `outputMode: "low"` (or the deprecated `displayVerbosity: "low"`) to reduce intermediate streaming updates.
---
@ -88,26 +88,6 @@ If the download returns an HTML login page instead of binary audio, the `files:r
---
### `/outputmode` command does nothing or returns "command not found"
**Symptoms:** Typing `/outputmode` shows no autocomplete, or Slack says the command is not found.
**Cause:** The `/outputmode` slash command must be registered in the Slack app's configuration before Slack delivers its payloads to OpenACP.
**Solution:**
1. In the [Slack API dashboard](https://api.slack.com/apps), open your app.
2. Go to **Slash Commands** in the left sidebar.
3. Click **Create New Command** and fill in:
- **Command**: `/outputmode`
- **Request URL**: leave blank (Socket Mode delivers the payload via WebSocket)
- **Short Description**: `Change output verbosity`
- **Usage Hint**: `[low|medium|high]`
4. Click **Save**.
5. Reinstall the app: **Settings → Install App → Reinstall to Workspace**.
6. Restart OpenACP.
---
### Channel creation fails or produces duplicate channels
**Symptoms:** Each restart creates a new `#openacp-…` channel, or channel creation fails with a permissions error.

View File

@ -14,7 +14,7 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Solution:**
1. Open your Telegram group → **Edit → Administrators** → add your bot and enable at minimum "Manage Topics".
2. Confirm the chat ID in `~/.openacp/config.json` matches the group. The ID of a group is negative (e.g., `-1001234567890`).
2. Confirm the chat ID in `~/.openacp/config.json` matches the group. The ID of a supergroup is negative (e.g., `-1001234567890`).
3. Restart OpenACP after making changes.
---
@ -23,42 +23,25 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Symptoms:** OpenACP logs show `Not enough rights` or `TOPIC_CLOSED` errors when trying to send messages.
**Cause:** The bot lacks administrator permissions in the group, or Topics are not enabled.
**Cause:** The bot lacks administrator permissions in the group, or topics (forum mode) are not enabled.
**Solution:**
1. Promote the bot to administrator in the group settings.
2. Enable Topics: **Group Settings → Edit → Topics**.
3. In the bot's admin settings, ensure "Manage Topics" is enabled.
2. Enable Topics: **Group Settings → Topics → Enable**.
3. The group must be a **supergroup** — regular groups do not support topics. Convert it via **Group Settings → Advanced → Convert to Supergroup**.
---
### Topics are not created on startup
**Symptoms:** OpenACP starts but no "Notifications" or "Assistant" topics appear.
**Symptoms:** OpenACP starts without error but no "Notifications" or "Assistant" topics appear in the group.
**Cause:** Either Topics are not enabled on the group, or the bot lacks the "Manage Topics" admin permission.
**New behavior (automatic):** OpenACP detects this at startup and sends a message to the group's **General** topic listing exactly what needs to be fixed. It then retries every 30 seconds automatically. Once the issues are resolved, topics are created and a confirmation message is sent.
**If you don't see the setup message:**
1. Confirm the bot is a member of the group.
2. Check logs for error details.
3. Run `openacp doctor` to diagnose.
---
### Bot cannot manage topics
**Symptoms:** Topics are enabled, but the bot still cannot create session topics. Logs may show `Not enough rights to manage forum topics`.
**Cause:** The bot is an admin but the "Manage Topics" permission is not enabled in its admin role.
**Cause:** The group does not have forum/topics mode enabled, or the bot is not an admin with topic management rights.
**Solution:**
1. Open the group in Telegram.
2. Go to **Group Settings → Administrators**.
3. Select your bot.
4. Enable the **Manage Topics** toggle.
5. Save. OpenACP will detect this within 30 seconds and complete setup automatically.
1. Enable forum mode: **Group Settings → Topics → Enable**.
2. Ensure the bot has "Manage Topics" permission under its administrator role.
3. Delete any stale `notificationTopicId` / `assistantTopicId` values from `~/.openacp/config.json` so OpenACP recreates them on next start.
---
@ -71,7 +54,7 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Solution:**
1. Add the bot to your group if you haven't already.
2. Run `openacp doctor` — it calls `getChat` and reports the exact error from the Telegram API.
3. If the ID looks correct, check that it is a negative integer for groups.
3. If the ID looks correct, check that it is a negative integer for supergroups.
---
@ -109,7 +92,7 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Solution:**
1. Ensure the bot is running — buttons expire after the bot restarts if not answered.
2. If buttons appear but clicking does nothing, check logs for `Telegram bot error` entries that may indicate the bot token has been revoked.
3. Re-run setup (`openacp onboard`) to regenerate configuration if the token is suspect.
3. Re-run setup (`openacp setup`) to regenerate configuration if the token is suspect.
---

View File

@ -59,29 +59,6 @@ Pass the agent name to `/new` to use a specific agent for a session:
If you have only one agent installed, it is selected automatically.
## Switching agents mid-conversation
Use `/switch` to change the agent handling the current session without starting a new thread or topic:
```
/switch # show a menu of available agents
/switch claude # switch directly to the claude agent
/switch gemini # switch directly to the gemini agent
```
The conversation history from the current session is automatically injected into the new agent, so it has full context of what was discussed. If you switch back to a previously used agent without having sent any new user prompts since the last switch, the old session is resumed (provided the agent supports resume). Otherwise a new session is started with the history prepended.
To label messages in the history with the agent name that produced them, use:
```
/switch label on # enable agent name labels
/switch label off # disable agent name labels
```
This is controlled globally by the `agentSwitch.labelHistory` config option (default: `true`).
For full details see [Agent Switch](../features/agent-switch.md).
## Default agent
The default agent is used when you create a session without specifying one. Configure it in `~/.openacp/config.json`:

View File

@ -19,9 +19,9 @@ OpenACP responds to commands sent in your chat platform. This page covers every
| `/doctor` | Yes | Yes | Run system diagnostics |
| `/tunnel` | Yes | No | Create a public URL for a local port |
| `/tunnels` | Yes | No | List active tunnels |
| `/enable_bypass` | Yes | No | Auto-approve all permissions |
| `/disable_bypass` | Yes | No | Restore normal permission prompts |
| `/bypass` | No | Yes | Toggle bypass permissions (Discord) |
| `/enable_dangerous` | Yes | No | Auto-approve all permissions |
| `/disable_dangerous` | Yes | No | Restore normal permission prompts |
| `/dangerous` | No | Yes | Toggle dangerous mode (Discord) |
| `/text_to_speech` | Yes | No | Toggle TTS for a session |
| `/tts` | No | Yes | Toggle TTS (Discord) |
| `/outputmode` | Yes | Yes | Set output detail level (replaces `/verbosity`) |
@ -29,11 +29,6 @@ OpenACP responds to commands sent in your chat platform. This page covers every
| `/usage` | Yes | No | View token usage and cost |
| `/archive` | Yes | No | Archive a session topic |
| `/summary` | Yes | No | Generate an AI summary of a session |
| `/mode` | Yes | Yes | Switch agent mode (code, architect, etc.) |
| `/model` | Yes | Yes | Switch agent model |
| `/thought` | Yes | Yes | Toggle thinking/reasoning mode |
| `/dangerous` | Yes | Yes | Toggle dangerous/bypass permissions mode |
| `/switch` | Yes | Yes | Switch to a different agent mid-conversation |
| `/handoff` | Yes | Yes | Continue session in your terminal |
| `/integrate` | Yes | Yes | Manage agent integrations |
| `/restart` | Yes | Yes | Restart OpenACP |
@ -55,7 +50,7 @@ Create a new agent session. If you omit arguments, OpenACP walks you through an
/new claude ~/code/my-project # create directly
```
On Telegram, each session gets its own topic. On Discord, a new thread is created in the configured channel.
On Telegram, each session gets its own forum topic. On Discord, a new thread is created in the configured channel.
### `/newchat`
@ -132,9 +127,9 @@ Create a public HTTPS URL for a local port. Useful when an agent starts a dev se
List all active tunnels with their public URLs and stop buttons.
### `/enable_bypass` / `/disable_bypass` (Telegram) · `/bypass` (Discord)
### `/enable_dangerous` / `/disable_dangerous` (Telegram) · `/dangerous` (Discord)
Toggle bypass permissions for the current session. When enabled, all permission requests are auto-approved without showing buttons. Run inside a session topic. See [Permissions](permissions.md) for details.
Toggle dangerous mode for the current session. When enabled, all permission requests are auto-approved without showing buttons. Run inside a session topic. See [Permissions](permissions.md) for details.
### `/text_to_speech [on|off]` (Telegram) · `/tts [on|off]` (Discord)
@ -142,21 +137,18 @@ Toggle text-to-speech for the current session. Without an argument, enables TTS
### `/outputmode low|medium|high`
Set how much detail OpenACP shows for agent activity. Supports a 3-level cascade: session override → adapter default → global default.
Set how much detail OpenACP shows for agent activity. You can also set a per-session override:
```
/outputmode low # set adapter default to low
/outputmode high # set adapter default to high
/outputmode reset # reset adapter default to global default
/outputmode session high # override for the current session only
/outputmode session reset # clear the session override
/outputmode low # set globally for this channel
/outputmode high # show full detail including inline output
/outputmode session high # override for the current session only
/outputmode session reset # clear the session override
```
- `low` — compact icon grid (minimal noise)
- `medium` — tool titles, descriptions, output summaries (default)
- `high` — full inline output, plan list, viewer links for long results, thinking viewer link
On Discord, an action row with `[🔇 Low] [📊 Medium] [🔍 High] [❌ Cancel]` buttons appears below the tool card while the agent is working, so you can switch mode without typing a command.
- `low` — minimal output, title only
- `medium` — balanced (default)
- `high` — full detail including inline output for short results, viewer links for long output
### `/verbosity low|medium|high` (deprecated)
@ -168,71 +160,12 @@ Show a token usage and cost report. Without arguments, shows today, this week, a
### `/archive` (Telegram only)
Archive the current session: stops the agent, marks the session as cancelled, and permanently deletes the Telegram topic. This cannot be undone.
Archive the current session: stops the agent, removes the session record, and deletes the Telegram topic. This cannot be undone.
### `/summary` (Telegram only)
Ask the agent to summarize what it has accomplished in the current session. Works inside a session topic.
### `/mode [mode-name]`
Switch the agent's operating mode. Without an argument, shows a menu of available modes declared by the agent (e.g., `code`, `architect`, `ask`).
```
/mode # show available modes
/mode code # switch to code mode
/mode architect # switch to architect mode
```
Available modes depend on the agent — they are declared via the ACP config options protocol.
### `/model [model-name]`
Switch the agent's model. Without an argument, shows available models.
```
/model # show available models
/model claude-sonnet # switch to a specific model
```
### `/thought [on|off]`
Toggle the agent's thinking/reasoning mode. When enabled, the agent shows its reasoning process.
```
/thought # toggle thinking mode
/thought on # enable thinking
/thought off # disable thinking
```
### `/dangerous [on|off]`
Toggle dangerous/bypass permissions mode for the current session. When enabled, the agent can perform destructive operations without confirmation prompts. This is equivalent to `/bypass` but routed through the agent's config options when available.
```
/dangerous # toggle dangerous mode
/dangerous on # enable (auto-approve all permissions)
/dangerous off # disable (restore normal prompts)
```
### `/switch [agent-name | label on|off]`
Switch to a different agent mid-conversation. The current conversation history is injected into the new agent so context is preserved.
```
/switch # show a menu of available agents
/switch claude # switch directly to the claude agent
/switch gemini # switch directly to the gemini agent
/switch label on # enable agent name labels in history during switches
/switch label off # disable agent name labels
```
If you switch back to a previously used agent without having sent any user prompts in the current session, the old session is resumed (if the agent supports resume). Otherwise a new session is created with the conversation history injected.
The session thread or topic remains the same across all switches — only the agent handling the conversation changes.
See [Agent Switch](../features/agent-switch.md) for the full feature guide.
### `/handoff`
Generate a terminal command to continue the current session in your local terminal. The agent session ID is included so context is preserved.

View File

@ -23,21 +23,21 @@ If you do not respond to a permission request within **10 minutes**, it is autom
This timeout exists to prevent sessions from blocking indefinitely when you are not present.
## Bypass permissions
## Dangerous mode
If you trust the agent completely for a session and do not want to approve each action individually, you can enable bypass permissions:
If you trust the agent completely for a session and do not want to approve each action individually, you can enable dangerous mode:
**Telegram:**
```
/enable_bypass # enable auto-approval
/disable_bypass # restore normal prompts
/enable_dangerous # enable auto-approval
/disable_dangerous # restore normal prompts
```
**Via the session control keyboard:** Tap the "Enable Bypass Permissions" button that appears in the session setup message.
**Via the session control keyboard:** Tap the "Enable Dangerous Mode" button that appears in the session setup message.
When bypass permissions is on, all permission requests are auto-approved immediately without showing buttons. The session topic shows a warning.
When dangerous mode is on, all permission requests are auto-approved immediately without showing buttons. The session topic shows a warning.
Bypass permissions is **per-session** — it does not affect other sessions and resets when the session ends.
Dangerous mode is **per-session** — it does not affect other sessions and resets when the session ends.
Use this only when you have reviewed the agent's plan and are confident in what it will do. Common use case: running a long automated task where interruptions for permission approval would be impractical.
@ -47,8 +47,8 @@ Permission approvals are logged. Use `/status` to see the current session state,
For server-wide access controls (user allowlists, session limits), see [Security](../self-hosting/security.md).
## Disabling bypass permissions
## Disabling dangerous mode
Run `/disable_bypass` (Telegram) or `/bypass` (Discord) inside the session topic, or tap the "Disable Bypass Permissions" button in the session control keyboard.
Run `/disable_dangerous` (Telegram) or `/dangerous` (Discord) inside the session topic, or tap the "Disable Dangerous Mode" button in the session control keyboard.
Normal permission prompts resume immediately.

View File

@ -15,16 +15,21 @@ If you have multiple agents installed, an inline keyboard lets you pick one. You
## Session lifecycle
A session goes through several stages during its life:
Sessions move through a defined set of states:
1. **Starting up** — The session is being created and the AI agent is warming up. This usually takes a few seconds.
2. **Active** — The session is ready. You can send messages and the agent will respond. This is where you spend most of your time.
3. **Done** — The agent finished its work. The session topic stays open for reference.
```
initializing → active → finished
↘ cancelled
↘ error → active (recoverable)
```
Sometimes things go differently:
- **Error** — Something went wrong, but you can usually recover by sending another message. OpenACP will try to reconnect the agent automatically.
- **Cancelled** — You stopped the session with `/cancel`. The session topic stays open and you can start a new one.
| State | Meaning |
|---|---|
| `initializing` | Session is starting; agent subprocess is warming up |
| `active` | Ready for prompts; agent is processing or waiting |
| `error` | An error occurred; may be recoverable |
| `cancelled` | Prompt was aborted; session is still alive |
| `finished` | Session ended normally |
Use `/status` inside a session topic to see the current state.
@ -48,22 +53,7 @@ Sessions have an inactivity timeout (default: 60 minutes). If no prompt is sent
Sessions that are `finished` or have been idle since a restart can often be resumed by simply sending a message in the existing topic or thread. OpenACP will reconnect to the agent process if possible.
Sessions that went offline (e.g., after a server restart) are automatically resumed when you send a message to their topic. This happens transparently — you do not need to manually restart the session.
For richer resume with full conversation history, use `/resume` (Telegram only). This loads context from Entire checkpoints or OpenACP's built-in history recorder — previous sessions' work is injected into the new session's context window. See the `/resume` section in [Chat Commands](chat-commands.md) for query formats.
## Session settings
Some agents let you change settings mid-conversation — like switching between different modes or models:
```
/mode # show available modes (e.g., code, architect)
/model # show available models
/thought # toggle thinking/reasoning mode
/dangerous # toggle bypass permissions
```
Available options depend on the agent you are using. When an agent updates its available options, the session reflects the changes automatically.
For richer resume with full conversation history, use `/resume` (Telegram only). This loads context from Entire checkpoints — previous sessions' work is injected into the new session's context window. See the `/resume` section in [Chat Commands](chat-commands.md) for query formats.
## Cancelling a prompt

Binary file not shown.

Before

Width:  |  Height:  |  Size: 951 KiB

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,554 +0,0 @@
# App Connectivity Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Enable app clients (desktop/web) to discover and connect to running OpenACP instances via localhost auto-discovery or remote links. Implement `openacp remote` CLI command for generating access tokens with QR codes and connection links.
**Architecture:** CLI command reads instance registry, generates JWT via API, auto-starts tunnel if needed, and outputs 3 link formats + ASCII QR code. A discovery utility reads `~/.openacp/instances.json` to find running instances by checking `api.port` files and health endpoints.
**Tech Stack:** qrcode-terminal (ASCII QR), existing instance-registry, existing tunnel plugin, existing API auth system
**Spec:** [docs/superpowers/specs/2026-03-31-app-connectivity-design.md](../specs/2026-03-31-app-connectivity-design.md)
**Depends on:** [Plan 1: API Server Core](./2026-03-31-api-server-core.md), [Plan 2: Auth System](./2026-03-31-auth-system.md)
---
## File Structure
```
src/
cli/
commands/
remote.ts — CREATE: `openacp remote` CLI command
core/
instance-discovery.ts — CREATE: Discover running instances from registry
```
---
## Task 1: Install QR Code Dependency
**Files:**
- Modify: `package.json`
- [ ] **Step 1: Install qrcode-terminal**
```bash
pnpm add qrcode-terminal
pnpm add -D @types/qrcode-terminal
```
If `@types/qrcode-terminal` doesn't exist, the implementing agent should check the package exports. If the package has no types, create a minimal declaration file at `src/types/qrcode-terminal.d.ts`:
```typescript
declare module 'qrcode-terminal' {
export function generate(text: string, opts?: { small?: boolean }, callback?: (qrcode: string) => void): void;
}
```
- [ ] **Step 2: Verify build**
```bash
pnpm build
```
Expected: Build succeeds.
- [ ] **Step 3: Commit**
```bash
git add package.json pnpm-lock.yaml
git commit -m "chore: add qrcode-terminal for remote access QR code generation"
```
---
## Task 2: Create Instance Discovery Utility
**Files:**
- Create: `src/core/instance-discovery.ts`
- Test: `src/core/__tests__/instance-discovery.test.ts`
- [ ] **Step 1: Write failing tests for instance discovery**
```typescript
// src/core/__tests__/instance-discovery.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { discoverRunningInstances, type DiscoveredInstance } from '../instance-discovery.js';
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import http from 'node:http';
describe('instance-discovery', () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = await mkdtemp(join(tmpdir(), 'discovery-'));
});
afterEach(async () => {
await rm(tmpDir, { recursive: true, force: true });
});
it('returns empty array when no instances registered', async () => {
const registryPath = join(tmpDir, 'instances.json');
await writeFile(registryPath, JSON.stringify({ version: 1, instances: {} }));
const instances = await discoverRunningInstances(registryPath);
expect(instances).toHaveLength(0);
});
it('discovers a running instance with api.port file', async () => {
// Create a temporary HTTP server to simulate health endpoint
const server = http.createServer((req, res) => {
if (req.url === '/api/v1/system/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
}
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as any).port;
try {
// Create instance directory with api.port file
const instanceRoot = join(tmpDir, 'instance1');
await mkdir(instanceRoot, { recursive: true });
await writeFile(join(instanceRoot, 'api.port'), String(port));
await writeFile(
join(instanceRoot, 'config.json'),
JSON.stringify({ instanceName: 'Test Instance' }),
);
// Create registry pointing to instance
const registryPath = join(tmpDir, 'instances.json');
await writeFile(
registryPath,
JSON.stringify({
version: 1,
instances: { test: { id: 'test', root: instanceRoot } },
}),
);
const instances = await discoverRunningInstances(registryPath);
expect(instances).toHaveLength(1);
expect(instances[0].id).toBe('test');
expect(instances[0].name).toBe('Test Instance');
expect(instances[0].port).toBe(port);
expect(instances[0].running).toBe(true);
} finally {
server.close();
}
});
it('skips instances without api.port file', async () => {
const instanceRoot = join(tmpDir, 'stopped-instance');
await mkdir(instanceRoot, { recursive: true });
// No api.port file — instance not running
const registryPath = join(tmpDir, 'instances.json');
await writeFile(
registryPath,
JSON.stringify({
version: 1,
instances: { stopped: { id: 'stopped', root: instanceRoot } },
}),
);
const instances = await discoverRunningInstances(registryPath);
expect(instances).toHaveLength(0);
});
});
```
- [ ] **Step 2: Run tests to verify they fail**
```bash
pnpm test -- src/core/__tests__/instance-discovery.test.ts
```
Expected: FAIL.
- [ ] **Step 3: Implement instance discovery**
```typescript
// src/core/instance-discovery.ts
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
export interface DiscoveredInstance {
id: string;
root: string;
name: string;
port: number;
running: boolean;
}
interface RegistryFile {
version: number;
instances: Record<string, { id: string; root: string }>;
}
export async function discoverRunningInstances(
registryPath: string,
): Promise<DiscoveredInstance[]> {
let registry: RegistryFile;
try {
const data = await readFile(registryPath, 'utf-8');
registry = JSON.parse(data);
} catch {
return [];
}
const discovered: DiscoveredInstance[] = [];
for (const entry of Object.values(registry.instances)) {
try {
// Check if api.port file exists (indicates running instance)
const portStr = await readFile(join(entry.root, 'api.port'), 'utf-8');
const port = parseInt(portStr.trim(), 10);
if (isNaN(port)) continue;
// Health check
const isHealthy = await checkHealth(port);
if (!isHealthy) continue;
// Read instance name from config
let name = entry.id;
try {
const configData = await readFile(join(entry.root, 'config.json'), 'utf-8');
const config = JSON.parse(configData);
if (config.instanceName) {
name = config.instanceName;
}
} catch {
// Config might not exist or be unreadable
}
discovered.push({
id: entry.id,
root: entry.root,
name,
port,
running: true,
});
} catch {
// api.port doesn't exist or can't be read — instance not running
continue;
}
}
return discovered;
}
async function checkHealth(port: number): Promise<boolean> {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3000);
const response = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`, {
signal: controller.signal,
});
clearTimeout(timeout);
return response.ok;
} catch {
return false;
}
}
```
- [ ] **Step 4: Run tests to verify they pass**
```bash
pnpm test -- src/core/__tests__/instance-discovery.test.ts
```
Expected: All 3 tests PASS.
- [ ] **Step 5: Commit**
```bash
git add src/core/instance-discovery.ts src/core/__tests__/instance-discovery.test.ts
git commit -m "feat(connectivity): add instance discovery utility for running instances"
```
---
## Task 3: Implement `openacp remote` CLI Command
**Files:**
- Create: `src/cli/commands/remote.ts`
- [ ] **Step 1: Examine existing CLI command pattern**
Read an existing command (e.g., `src/cli/commands/status.ts` or `src/cli/commands/tunnel.ts`) to understand:
- Export pattern (named export, command definition structure)
- How CLI flags are parsed
- How instance context is resolved
- How output is formatted
- [ ] **Step 2: Implement remote command**
```typescript
// src/cli/commands/remote.ts
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import qrcode from 'qrcode-terminal';
// The implementing agent must match the exact CLI command definition pattern
// used in this project. Below is a reference implementation — adjust to match
// the project's command registration API.
export async function remoteCommand(opts: {
role?: string;
expire?: string;
scopes?: string;
name?: string;
noTunnel?: boolean;
noQr?: boolean;
instance?: string;
instanceRoot: string;
}): Promise<void> {
const role = opts.role ?? 'admin';
const expire = opts.expire ?? '24h';
const instanceRoot = opts.instanceRoot;
// 1. Check API server is running
let port: number;
try {
const portStr = await readFile(join(instanceRoot, 'api.port'), 'utf-8');
port = parseInt(portStr.trim(), 10);
} catch {
console.error('API server not running. Start with: openacp start');
process.exit(1);
}
// Verify health
try {
const res = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`);
if (!res.ok) throw new Error('Health check failed');
} catch {
console.error('API server not responding on port', port);
process.exit(1);
}
// 2. Read secret token
let secret: string;
try {
secret = (await readFile(join(instanceRoot, 'api-secret'), 'utf-8')).trim();
} catch {
console.error('Cannot read API secret. Is the instance set up?');
process.exit(1);
}
// 3. Generate name
const now = new Date();
const tokenName =
opts.name ??
`remote-${String(now.getHours()).padStart(2, '0')}h${String(now.getMinutes()).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}-${String(now.getMonth() + 1).padStart(2, '0')}-${now.getFullYear()}`;
// 4. Generate JWT via API
const tokenRes = await fetch(`http://127.0.0.1:${port}/api/v1/auth/tokens`, {
method: 'POST',
headers: {
Authorization: `Bearer ${secret}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
role,
name: tokenName,
expire,
...(opts.scopes ? { scopes: opts.scopes.split(',').map((s) => s.trim()) } : {}),
}),
});
if (!tokenRes.ok) {
const err = await tokenRes.json();
console.error('Failed to generate token:', err);
process.exit(1);
}
const tokenData = (await tokenRes.json()) as {
accessToken: string;
tokenId: string;
expiresAt: string;
refreshDeadline: string;
};
// 5. Tunnel handling
let tunnelUrl: string | null = null;
if (!opts.noTunnel) {
tunnelUrl = await getTunnelUrl(port, secret);
}
// 6. Generate links
const localLink = `http://localhost:${port}?token=${tokenData.accessToken}`;
const tunnelLink = tunnelUrl ? `${tunnelUrl}?token=${tokenData.accessToken}` : null;
const tunnelHost = tunnelUrl ? new URL(tunnelUrl).host : null;
const appLink = tunnelHost
? `openacp://connect?host=${tunnelHost}&token=${tokenData.accessToken}`
: `openacp://connect?host=localhost&port=${port}&token=${tokenData.accessToken}`;
// 7. Output
console.log('');
console.log('╔══════════════════════════════════════════════════════════════╗');
console.log('║ OpenACP Remote Access ║');
console.log('╠══════════════════════════════════════════════════════════════╣');
console.log(`║ Token: ${tokenName.padEnd(49)}║`);
console.log(`║ Role: ${role.padEnd(49)}║`);
console.log(`║ Expires: ${new Date(tokenData.expiresAt).toLocaleString().padEnd(49)}║`);
console.log(`║ Refresh: until ${new Date(tokenData.refreshDeadline).toLocaleString().padEnd(43)}║`);
console.log('║ ║');
console.log('║ Local: ║');
console.log(`║ ${localLink}`);
console.log('║ ║');
if (tunnelLink) {
console.log('║ Tunnel: ║');
console.log(`║ ${tunnelLink}`);
console.log('║ ║');
}
console.log('║ App: ║');
console.log(`║ ${appLink}`);
console.log('║ ║');
console.log('╚══════════════════════════════════════════════════════════════╝');
// 8. QR code
if (!opts.noQr) {
const qrLink = tunnelLink ?? localLink;
console.log('');
console.log('Scan QR code to connect:');
qrcode.generate(qrLink, { small: true });
}
console.log('');
}
async function getTunnelUrl(port: number, secret: string): Promise<string | null> {
try {
// Check if tunnel is already running via API
const res = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`, {
headers: { Authorization: `Bearer ${secret}` },
});
if (!res.ok) return null;
const health = (await res.json()) as { tunnel?: { url?: string } };
if (health.tunnel?.url) {
return health.tunnel.url;
}
// Tunnel not running — try to start it
// The implementing agent should check if there's a tunnel start API endpoint
// or if the tunnel plugin needs to be accessed differently
const tunnelRes = await fetch(`http://127.0.0.1:${port}/api/v1/tunnel/start`, {
method: 'POST',
headers: { Authorization: `Bearer ${secret}` },
});
if (tunnelRes.ok) {
const tunnelData = (await tunnelRes.json()) as { url?: string };
return tunnelData.url ?? null;
}
return null;
} catch {
return null;
}
}
```
Note: The implementing agent must:
- Match the exact CLI command registration pattern (check `src/cli.ts` or an existing command)
- Verify how flags are parsed (yargs, commander, custom?)
- Verify the tunnel API endpoint exists and its exact response format
- Check the health endpoint response shape for tunnel URL
- [ ] **Step 3: Register the remote command in CLI**
Check `src/cli.ts` to understand how commands are registered. Add `remote` command with flags:
- `--role <role>` (default: admin)
- `--expire <duration>` (default: 24h)
- `--scopes <scopes>` (comma-separated)
- `--name <label>`
- `--no-tunnel`
- `--no-qr`
- `--instance <id>`
- [ ] **Step 4: Verify build**
```bash
pnpm build
```
- [ ] **Step 5: Commit**
```bash
git add src/cli/commands/remote.ts src/cli.ts
git commit -m "feat(connectivity): add openacp remote CLI command with token and QR generation"
```
---
## Task 4: Manual End-to-End Test
This task is a manual verification that the full flow works.
- [ ] **Step 1: Start OpenACP with API server**
```bash
pnpm start
```
- [ ] **Step 2: Run openacp remote**
```bash
pnpm start -- remote
```
Expected output:
- Token info (name, role, expiry, refresh deadline)
- Local link with JWT
- Tunnel link (if tunnel configured) or skip
- App link with openacp:// scheme
- QR code (ASCII art)
- [ ] **Step 3: Test local link**
```bash
# Copy the local link and test it
curl "http://localhost:<port>/api/v1/auth/me" -H "Authorization: Bearer <jwt-from-link>"
```
Expected: Returns `{ type: "jwt", role: "admin", ... }`
- [ ] **Step 4: Test token refresh**
```bash
curl -X POST "http://localhost:<port>/api/v1/auth/refresh" -H "Authorization: Bearer <jwt>"
```
Expected: Returns new access token with same tokenId.
- [ ] **Step 5: Test token revocation**
```bash
# List tokens
curl "http://localhost:<port>/api/v1/auth/tokens" -H "Authorization: Bearer <secret>"
# Revoke the token
curl -X DELETE "http://localhost:<port>/api/v1/auth/tokens/<tokenId>" -H "Authorization: Bearer <secret>"
# Verify old JWT no longer works
curl "http://localhost:<port>/api/v1/auth/me" -H "Authorization: Bearer <old-jwt>"
```
Expected: 401 "Token revoked"
- [ ] **Step 6: Commit any fixes**
```bash
git add -A
git commit -m "fix(connectivity): address issues found during manual testing"
```

File diff suppressed because it is too large Load Diff

View File

@ -1,847 +0,0 @@
# Core Refactor Phase 1 — Split `core.ts` + Organize Instance Files
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Reduce `core.ts` from 929 to ~400 lines by extracting AgentSwitchHandler, moving lazy resume to SessionFactory, moving convenience creation methods to SessionFactory, and grouping instance-* files into `core/instance/`.
**Architecture:** Extract responsibilities into focused modules while keeping OpenACPCore as thin orchestrator. All public method signatures on OpenACPCore stay the same — only internal delegation changes.
**Tech Stack:** TypeScript, Vitest, ESM (.js extensions)
**Spec:** `docs/superpowers/specs/2026-03-31-core-refactor-design.md`
---
### Task 1: Create branch and group instance-* files into `core/instance/`
**Files:**
- Create: `src/core/instance/index.ts`
- Move: `src/core/instance-context.ts` → `src/core/instance/instance-context.ts`
- Move: `src/core/instance-registry.ts` → `src/core/instance/instance-registry.ts`
- Move: `src/core/instance-discovery.ts` → `src/core/instance/instance-discovery.ts`
- Move: `src/core/instance-copy.ts` → `src/core/instance/instance-copy.ts`
- Move: `src/core/__tests__/instance-context.test.ts` → `src/core/instance/__tests__/instance-context.test.ts`
- Move: `src/core/__tests__/instance-registry.test.ts` → `src/core/instance/__tests__/instance-registry.test.ts`
- Move: `src/core/__tests__/instance-discovery.test.ts` → `src/core/instance/__tests__/instance-discovery.test.ts`
- Move: `src/core/__tests__/instance-copy.test.ts` → `src/core/instance/__tests__/instance-copy.test.ts`
- Move: `src/core/__tests__/multi-instance-flows.test.ts` → `src/core/instance/__tests__/multi-instance-flows.test.ts`
- [ ] **Step 1: Create feature branch**
```bash
cd /Users/lucas/openacp-workspace/OpenACP
git checkout -b refactor/core-phase1
```
- [ ] **Step 2: Create directory structure and move files**
```bash
mkdir -p src/core/instance/__tests__
git mv src/core/instance-context.ts src/core/instance/instance-context.ts
git mv src/core/instance-registry.ts src/core/instance/instance-registry.ts
git mv src/core/instance-discovery.ts src/core/instance/instance-discovery.ts
git mv src/core/instance-copy.ts src/core/instance/instance-copy.ts
git mv src/core/__tests__/instance-context.test.ts src/core/instance/__tests__/instance-context.test.ts
git mv src/core/__tests__/instance-registry.test.ts src/core/instance/__tests__/instance-registry.test.ts
git mv src/core/__tests__/instance-discovery.test.ts src/core/instance/__tests__/instance-discovery.test.ts
git mv src/core/__tests__/instance-copy.test.ts src/core/instance/__tests__/instance-copy.test.ts
git mv src/core/__tests__/multi-instance-flows.test.ts src/core/instance/__tests__/multi-instance-flows.test.ts
```
- [ ] **Step 3: Create `src/core/instance/index.ts`**
```typescript
export {
type InstanceContext,
type CreateInstanceContextOpts,
type ResolveOpts,
createInstanceContext,
generateSlug,
resolveInstanceRoot,
getGlobalRoot,
} from './instance-context.js'
export { InstanceRegistry, type InstanceRegistryEntry } from './instance-registry.js'
export { discoverRunningInstances, type DiscoveredInstance } from './instance-discovery.js'
export { copyInstance, type CopyOptions } from './instance-copy.js'
```
- [ ] **Step 4: Update all import paths**
Update these files to import from the new location. Each file's old and new import:
**`src/core/core.ts` (line 29):**
- Old: `import type { InstanceContext } from "./instance-context.js";`
- New: `import type { InstanceContext } from "./instance/instance-context.js";`
**`src/main.ts` (lines 5-6):**
- Old: `import type { InstanceContext } from './core/instance-context.js'`
`import { createInstanceContext, getGlobalRoot } from './core/instance-context.js'`
- New: `import type { InstanceContext } from './core/instance/instance-context.js'`
`import { createInstanceContext, getGlobalRoot } from './core/instance/instance-context.js'`
**`src/main.ts` (line 16):**
- Old: `import { InstanceRegistry } from './core/instance-registry.js'`
- New: `import { InstanceRegistry } from './core/instance/instance-registry.js'`
**`src/cli.ts` (line 34):**
- Old: `import { resolveInstanceRoot, getGlobalRoot } from './core/instance-context.js'`
- New: `import { resolveInstanceRoot, getGlobalRoot } from './core/instance/instance-context.js'`
**`src/cli/instance-hint.ts` (line 4):**
- Old: `import { getGlobalRoot } from '../core/instance-context.js'`
- New: `import { getGlobalRoot } from '../core/instance/instance-context.js'`
**`src/cli/commands/default.ts` (line 5):**
- Old: `import { createInstanceContext, getGlobalRoot } from '../../core/instance-context.js'`
- New: `import { createInstanceContext, getGlobalRoot } from '../../core/instance/instance-context.js'`
**`src/cli/commands/restart.ts` (line 5):**
- Old: `import { createInstanceContext, getGlobalRoot } from '../../core/instance-context.js'`
- New: `import { createInstanceContext, getGlobalRoot } from '../../core/instance/instance-context.js'`
**`src/cli/commands/status.ts` (lines 1-2):**
- Old: `import { InstanceRegistry } from '../../core/instance-registry.js'`
`import { getGlobalRoot } from '../../core/instance-context.js'`
- New: `import { InstanceRegistry } from '../../core/instance/instance-registry.js'`
`import { getGlobalRoot } from '../../core/instance/instance-context.js'`
**`src/cli/commands/remote.ts` (line 2):**
- Old: `import { InstanceRegistry } from '../../core/instance-registry.js'`
- New: `import { InstanceRegistry } from '../../core/instance/instance-registry.js'`
**`src/core/setup/wizard.ts` (lines 18-20):**
- Old: `import { generateSlug, getGlobalRoot } from "../instance-context.js";`
`import { InstanceRegistry } from "../instance-registry.js";`
`import { copyInstance } from "../instance-copy.js";`
- New: `import { generateSlug, getGlobalRoot } from "../instance/instance-context.js";`
`import { InstanceRegistry } from "../instance/instance-registry.js";`
`import { copyInstance } from "../instance/instance-copy.js";`
**`src/core/setup/setup-channels.ts` (line 2):**
- Old: `import { getGlobalRoot } from "../instance-context.js";`
- New: `import { getGlobalRoot } from "../instance/instance-context.js";`
**`src/core/config/config-migrations.ts` (line 4):**
- Old: `import { getGlobalRoot } from "../instance-context.js";`
- New: `import { getGlobalRoot } from "../instance/instance-context.js";`
**`src/core/config/config-registry.ts` (line 4):**
- Old: `import { getGlobalRoot } from "../instance-context.js";`
- New: `import { getGlobalRoot } from "../instance/instance-context.js";`
**`src/core/doctor/index.ts` (line 5):**
- Old: `import { getGlobalRoot } from "../instance-context.js";`
- New: `import { getGlobalRoot } from "../instance/instance-context.js";`
**Test files — update relative imports:**
`src/core/instance/__tests__/instance-context.test.ts`:
- Old: `from '../instance-context.js'`
- New: `from '../instance-context.js'` (no change — moved together)
`src/core/instance/__tests__/instance-registry.test.ts`:
- Old: `from '../instance-registry.js'`
- New: `from '../instance-registry.js'` (no change — moved together)
`src/core/instance/__tests__/instance-discovery.test.ts`:
- Old: `from '../instance-discovery.js'`
- New: `from '../instance-discovery.js'` (no change — moved together)
`src/core/instance/__tests__/instance-copy.test.ts`:
- Old: `from '../instance-copy.js'`
- New: `from '../instance-copy.js'` (no change — moved together)
`src/core/instance/__tests__/multi-instance-flows.test.ts`:
- Old: `from '../instance-registry.js'` and `from '../instance-copy.js'`
- New: `from '../instance-registry.js'` and `from '../instance-copy.js'` (no change — moved together)
- [ ] **Step 5: Build and run tests**
```bash
pnpm build && pnpm test
```
Expected: All tests pass, no build errors.
- [ ] **Step 6: Commit**
```bash
git add -A
git commit -m "refactor: group instance-* files into core/instance/"
```
---
### Task 2: Extract `AgentSwitchHandler` from `core.ts`
**Files:**
- Create: `src/core/agent-switch-handler.ts`
- Modify: `src/core/core.ts` (remove lines 609-809, add delegation)
- [ ] **Step 1: Create `src/core/agent-switch-handler.ts`**
```typescript
import type { AgentManager } from "./agents/agent-manager.js";
import type { SessionManager } from "./sessions/session-manager.js";
import type { ConfigManager } from "./config/config.js";
import type { SessionBridge } from "./sessions/session-bridge.js";
import type { Session } from "./sessions/session.js";
import type { IChannelAdapter } from "./channel.js";
import type { EventBus } from "./event-bus.js";
import type { MiddlewareChain } from "./plugin/middleware-chain.js";
import type { AgentEvent } from "./types.js";
import type { ContextManager } from "../plugins/context/context-manager.js";
import { getAgentCapabilities } from "./agents/agent-registry.js";
import { createChildLogger } from "./utils/log.js";
const log = createChildLogger({ module: "agent-switch" });
export interface AgentSwitchDeps {
sessionManager: SessionManager;
agentManager: AgentManager;
configManager: ConfigManager;
eventBus: EventBus;
adapters: Map<string, IChannelAdapter>;
bridges: Map<string, SessionBridge>;
createBridge: (session: Session, adapter: IChannelAdapter) => SessionBridge;
getMiddlewareChain: () => MiddlewareChain | undefined;
getService: <T>(name: string) => T | undefined;
}
export class AgentSwitchHandler {
private switchingLocks = new Set<string>();
constructor(private deps: AgentSwitchDeps) {}
async switch(sessionId: string, toAgent: string): Promise<{ resumed: boolean }> {
if (this.switchingLocks.has(sessionId)) {
throw new Error('Switch already in progress');
}
this.switchingLocks.add(sessionId);
try {
return await this.doSwitch(sessionId, toAgent);
} finally {
this.switchingLocks.delete(sessionId);
}
}
private async doSwitch(sessionId: string, toAgent: string): Promise<{ resumed: boolean }> {
const { sessionManager, agentManager, configManager, eventBus, adapters, bridges, createBridge } = this.deps;
const session = sessionManager.getSession(sessionId);
if (!session) throw new Error(`Session ${sessionId} not found`);
// Validate target agent exists before doing anything destructive
const agentDef = agentManager.getAgent(toAgent);
if (!agentDef) throw new Error(`Agent "${toAgent}" is not installed`);
const fromAgent = session.agentName;
// 1. Middleware: agent:beforeSwitch (blocking)
const middlewareChain = this.deps.getMiddlewareChain();
const result = await middlewareChain?.execute('agent:beforeSwitch', {
sessionId,
fromAgent,
toAgent,
}, async (payload) => payload);
if (middlewareChain && !result) throw new Error('Agent switch blocked by middleware');
// 2. Determine resume vs new
const lastEntry = session.findLastSwitchEntry(toAgent);
const caps = getAgentCapabilities(toAgent);
const canResume = !!(lastEntry && caps.supportsResume && lastEntry.promptCount === 0);
const resumed = canResume;
// Emit "starting" events so UI can reflect long-running switches
const startEvent: AgentEvent = {
type: "system_message",
message: `Switching from ${fromAgent} to ${toAgent}...`,
};
session.emit("agent_event", startEvent);
eventBus.emit("agent:event", { sessionId, event: startEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
status: "starting",
});
// 3. Disconnect bridge
const bridge = bridges.get(sessionId);
if (bridge) bridge.disconnect();
// Clear old agent's skill commands so they don't linger in the UI
const switchAdapter = adapters.get(session.channelId);
if (switchAdapter?.sendSkillCommands) {
await switchAdapter.sendSkillCommands(session.id, []);
}
// Clean up adapter-side per-session state (draft manager, activity tracker, etc.)
if (switchAdapter?.cleanupSessionState) {
await switchAdapter.cleanupSessionState(session.id);
}
// Capture pre-switch state for rollback
const fromAgentSessionId = session.agentSessionId;
// 4. Switch agent on session (with rollback on failure)
try {
await session.switchAgent(toAgent, async () => {
if (canResume) {
return agentManager.resume(toAgent, session.workingDirectory, lastEntry!.agentSessionId);
} else {
const instance = await agentManager.spawn(toAgent, session.workingDirectory);
// Inject context if context service available
try {
const contextService = this.deps.getService<ContextManager>('context');
if (contextService) {
const config = configManager.get();
const labelAgent = config.agentSwitch?.labelHistory ?? true;
const contextResult = await contextService.buildContext(
{ type: 'session', value: sessionId, repoPath: session.workingDirectory },
{ labelAgent },
);
if (contextResult?.markdown) {
session.setContext(contextResult.markdown);
}
}
} catch {
// Context injection is best-effort
}
return instance;
}
});
// On success, emit structured + system_message events
const successEvent: AgentEvent = {
type: "system_message",
message: resumed
? `Switched to ${toAgent} (resumed previous session).`
: `Switched to ${toAgent} (new session).`,
};
session.emit("agent_event", successEvent);
eventBus.emit("agent:event", { sessionId, event: successEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
status: "succeeded",
resumed,
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
// Emit failure events before attempting rollback so UI can show error state
const failedEvent: AgentEvent = {
type: "system_message",
message: `Failed to switch to ${toAgent}: ${errorMessage}`,
};
session.emit("agent_event", failedEvent);
eventBus.emit("agent:event", { sessionId, event: failedEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
status: "failed",
error: errorMessage,
});
// Rollback: try to restore the old agent so the session isn't left broken
try {
let rollbackInstance;
try {
rollbackInstance = await agentManager.resume(fromAgent, session.workingDirectory, fromAgentSessionId);
} catch {
rollbackInstance = await agentManager.spawn(fromAgent, session.workingDirectory);
}
const oldInstance = rollbackInstance;
session.agentSwitchHistory.pop();
session.agentInstance = oldInstance;
session.agentName = fromAgent;
session.agentSessionId = oldInstance.sessionId;
// Reconnect bridge after rollback
const adapter = adapters.get(session.channelId);
if (adapter) {
createBridge(session, adapter).connect();
}
log.warn({ sessionId, fromAgent, toAgent, err }, "Agent switch failed, rolled back to previous agent");
} catch (rollbackErr) {
session.fail(`Switch failed and rollback failed: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
log.error({ sessionId, fromAgent, toAgent, err, rollbackErr }, "Agent switch failed and rollback also failed");
}
throw err;
}
// 5. Reconnect bridge
if (bridge) {
const adapter = adapters.get(session.channelId);
if (adapter) {
createBridge(session, adapter).connect();
}
}
// 6. Persist
await sessionManager.patchRecord(sessionId, {
agentName: toAgent,
agentSessionId: session.agentSessionId,
firstAgent: session.firstAgent,
currentPromptCount: 0,
agentSwitchHistory: session.agentSwitchHistory,
});
// 7. Middleware: agent:afterSwitch (fire-and-forget)
middlewareChain?.execute('agent:afterSwitch', {
sessionId,
fromAgent,
toAgent,
resumed,
}, async (p) => p).catch(() => {});
return { resumed };
}
}
```
- [ ] **Step 2: Wire `AgentSwitchHandler` in `core.ts`**
Add import at top of `core.ts`:
```typescript
import { AgentSwitchHandler } from "./agent-switch-handler.js";
```
Add field in `OpenACPCore` class (after `sessionFactory` field):
```typescript
private agentSwitchHandler: AgentSwitchHandler;
```
Initialize in constructor (after `this.lifecycleManager` initialization, around line 127):
```typescript
this.agentSwitchHandler = new AgentSwitchHandler({
sessionManager: this.sessionManager,
agentManager: this.agentManager,
configManager: this.configManager,
eventBus: this.eventBus,
adapters: this.adapters,
bridges: this.bridges,
createBridge: (session, adapter) => this.createBridge(session, adapter),
getMiddlewareChain: () => this.lifecycleManager?.middlewareChain,
getService: <T>(name: string) => this.lifecycleManager.serviceRegistry.get<T>(name),
});
```
Replace `switchSessionAgent` and `_doSwitchSessionAgent` methods (lines 609-809) with:
```typescript
async switchSessionAgent(sessionId: string, toAgent: string): Promise<{ resumed: boolean }> {
return this.agentSwitchHandler.switch(sessionId, toAgent);
}
```
Remove `switchingLocks` field from `OpenACPCore` (line 46).
- [ ] **Step 3: Build and run tests**
```bash
pnpm build && pnpm test
```
Expected: All existing agent switch tests pass (`agent-switch.test.ts`, `session-switch.test.ts`, `session-bridge-switch.test.ts`, `core-orchestrator-comprehensive.test.ts`).
- [ ] **Step 4: Commit**
```bash
git add src/core/agent-switch-handler.ts src/core/core.ts
git commit -m "refactor: extract AgentSwitchHandler from core.ts"
```
---
### Task 3: Move lazy resume into SessionFactory
**Files:**
- Modify: `src/core/sessions/session-factory.ts`
- Modify: `src/core/core.ts`
- [ ] **Step 1: Add lazy resume to SessionFactory**
Add imports at top of `session-factory.ts`:
```typescript
import type { SessionStore } from "./session-store.js";
import type { IChannelAdapter } from "../channel.js";
```
Add new fields and constructor params to `SessionFactory`. Update the constructor:
```typescript
export class SessionFactory {
middlewareChain?: MiddlewareChain;
private resumeLocks: Map<string, Promise<Session | null>> = new Map();
constructor(
private agentManager: AgentManager,
private sessionManager: SessionManager,
private speechServiceAccessor: SpeechService | (() => SpeechService),
private eventBus: EventBus,
private instanceRoot?: string,
) {}
/** Injected by Core after construction — needed for lazy resume error feedback */
adapters?: Map<string, IChannelAdapter>;
/** Injected by Core after construction — needed for lazy resume store lookup */
sessionStore?: SessionStore | null;
/** Injected by Core — creates full session with thread + bridge + persist */
createFullSession?: (params: SessionCreateParams & { threadId?: string; createThread?: boolean }) => Promise<Session>;
```
Add these methods to `SessionFactory`:
```typescript
/**
* Get active session by thread, or attempt lazy resume from store.
* Used by adapter command handlers and handleMessage().
*/
async getOrResume(channelId: string, threadId: string): Promise<Session | null> {
const session = this.sessionManager.getSessionByThread(channelId, threadId);
if (session) return session;
return this.lazyResume(channelId, threadId);
}
private async lazyResume(channelId: string, threadId: string): Promise<Session | null> {
const store = this.sessionStore;
if (!store || !this.createFullSession) return null;
const lockKey = `${channelId}:${threadId}`;
// Check for existing resume in progress
const existing = this.resumeLocks.get(lockKey);
if (existing) return existing;
const record = store.findByPlatform(
channelId,
(p) => String(p.topicId) === threadId,
);
if (!record) {
log.debug({ threadId, channelId }, "No session record found for thread");
return null;
}
// Don't resume errored or cancelled sessions
if (record.status === "error" || record.status === "cancelled") {
log.debug({ threadId, sessionId: record.sessionId, status: record.status }, "Skipping resume of error session");
return null;
}
log.info({ threadId, sessionId: record.sessionId, status: record.status }, "Lazy resume: found record, attempting resume");
const resumePromise = (async (): Promise<Session | null> => {
try {
const session = await this.createFullSession!({
channelId: record.channelId,
agentName: record.agentName,
workingDirectory: record.workingDir,
resumeAgentSessionId: record.agentSessionId,
existingSessionId: record.sessionId,
initialName: record.name,
threadId,
});
session.activate();
session.dangerousMode = record.dangerousMode ?? false;
if (record.firstAgent) session.firstAgent = record.firstAgent;
if (record.agentSwitchHistory) session.agentSwitchHistory = record.agentSwitchHistory;
if (record.currentPromptCount != null) session.promptCount = record.currentPromptCount;
log.info({ sessionId: session.id, threadId }, "Lazy resume successful");
return session;
} catch (err) {
log.error({ err, record }, "Lazy resume failed");
// Send error feedback to user
const adapter = this.adapters?.get(channelId);
if (adapter) {
try {
await adapter.sendMessage(threadId, {
type: "error",
text: `⚠️ Failed to resume session: ${err instanceof Error ? err.message : String(err)}`,
});
} catch { /* best effort */ }
}
return null;
} finally {
this.resumeLocks.delete(lockKey);
}
})();
this.resumeLocks.set(lockKey, resumePromise);
return resumePromise;
}
```
- [ ] **Step 2: Wire SessionFactory in core.ts and remove old lazy resume**
In `core.ts` constructor, after `this.sessionFactory` creation and `this.lifecycleManager` setup (around line 127), add:
```typescript
// Wire lazy resume dependencies
this.sessionFactory.sessionStore = this.sessionStore;
this.sessionFactory.adapters = this.adapters;
this.sessionFactory.createFullSession = (params) => this.createSession(params);
```
Update `handleMessage()` — replace lines 281-297:
```typescript
// Find session by thread or lazy resume
let session = await this.sessionFactory.getOrResume(message.channelId, message.threadId);
if (!session) {
log.warn(
{ channelId: message.channelId, threadId: message.threadId },
"No session found for thread (in-memory miss + lazy resume returned null)",
);
return;
}
```
Update `getOrResumeSession()` — replace lines 817-821:
```typescript
async getOrResumeSession(channelId: string, threadId: string): Promise<Session | null> {
return this.sessionFactory.getOrResume(channelId, threadId);
}
```
Remove from `core.ts`:
- `private resumeLocks: Map<string, Promise<Session | null>> = new Map();` (line 45)
- The entire `private async lazyResume(message: IncomingMessage)` method (lines 823-911)
- [ ] **Step 3: Build and run tests**
```bash
pnpm build && pnpm test
```
Expected: All lazy resume tests pass (`lazy-resume.test.ts`, `core-orchestrator-comprehensive.test.ts` lazy resume suite).
- [ ] **Step 4: Commit**
```bash
git add src/core/sessions/session-factory.ts src/core/core.ts
git commit -m "refactor: move lazy resume from core.ts into SessionFactory"
```
---
### Task 4: Move convenience session creation methods to SessionFactory
**Files:**
- Modify: `src/core/sessions/session-factory.ts`
- Modify: `src/core/core.ts`
- [ ] **Step 1: Add convenience methods to SessionFactory**
Add import to `session-factory.ts`:
```typescript
import type { ConfigManager } from "../config/config.js";
import type { AgentCatalog } from "../agents/agent-catalog.js";
import type { ContextManager } from "../../plugins/context/context-manager.js";
import type { ContextQuery, ContextOptions, ContextResult } from "../../plugins/context/context-provider.js";
```
Add new fields (injected by Core after construction):
```typescript
/** Injected by Core — needed for resolving default agent and workspace */
configManager?: ConfigManager;
/** Injected by Core — needed for resolving agent definitions */
agentCatalog?: AgentCatalog;
/** Injected by Core — needed for context-aware session creation */
getContextManager?: () => ContextManager | undefined;
```
Add these methods to `SessionFactory`:
```typescript
async handleNewSession(
channelId: string,
agentName?: string,
workspacePath?: string,
options?: { createThread?: boolean },
): Promise<Session> {
if (!this.configManager || !this.agentCatalog || !this.createFullSession) {
throw new Error("SessionFactory not fully initialized");
}
const config = this.configManager.get();
const resolvedAgent = agentName || config.defaultAgent;
log.info({ channelId, agentName: resolvedAgent }, "New session request");
const agentDef = this.agentCatalog.resolve(resolvedAgent);
const resolvedWorkspace = this.configManager.resolveWorkspace(
workspacePath || agentDef?.workingDirectory,
);
return this.createFullSession({
channelId,
agentName: resolvedAgent,
workingDirectory: resolvedWorkspace,
...options,
});
}
/** NOTE: handleNewChat is currently dead code — never called outside core.ts itself.
* Moving it anyway for completeness; can be removed in a future cleanup. */
async handleNewChat(
channelId: string,
currentThreadId: string,
): Promise<Session | null> {
const currentSession = this.sessionManager.getSessionByThread(
channelId,
currentThreadId,
);
if (currentSession) {
return this.handleNewSession(
channelId,
currentSession.agentName,
currentSession.workingDirectory,
);
}
// Fallback: look up from store
const record = this.sessionManager.getRecordByThread(
channelId,
currentThreadId,
);
if (!record || record.status === "cancelled" || record.status === "error")
return null;
return this.handleNewSession(
channelId,
record.agentName,
record.workingDir,
);
}
async createSessionWithContext(params: {
channelId: string;
agentName: string;
workingDirectory: string;
contextQuery: ContextQuery;
contextOptions?: ContextOptions;
createThread?: boolean;
}): Promise<{ session: Session; contextResult: ContextResult | null }> {
if (!this.createFullSession) throw new Error("SessionFactory not fully initialized");
let contextResult: ContextResult | null = null;
const contextManager = this.getContextManager?.();
if (contextManager) {
try {
contextResult = await contextManager.buildContext(
params.contextQuery,
params.contextOptions,
);
} catch (err) {
log.warn({ err }, "Context building failed, proceeding without context");
}
}
const session = await this.createFullSession({
channelId: params.channelId,
agentName: params.agentName,
workingDirectory: params.workingDirectory,
createThread: params.createThread,
});
if (contextResult) {
session.setContext(contextResult.markdown);
}
return { session, contextResult };
}
```
- [ ] **Step 2: Wire new dependencies and delegate from core.ts**
In `core.ts` constructor, extend the wiring section:
```typescript
this.sessionFactory.configManager = this.configManager;
this.sessionFactory.agentCatalog = this.agentCatalog;
this.sessionFactory.getContextManager = () => this.lifecycleManager.serviceRegistry.get<ContextManager>('context');
```
Replace `handleNewSession`, `handleNewChat`, `createSessionWithContext` methods in `core.ts` with thin delegators:
```typescript
async handleNewSession(
channelId: string,
agentName?: string,
workspacePath?: string,
options?: { createThread?: boolean },
): Promise<Session> {
return this.sessionFactory.handleNewSession(channelId, agentName, workspacePath, options);
}
async handleNewChat(channelId: string, currentThreadId: string): Promise<Session | null> {
return this.sessionFactory.handleNewChat(channelId, currentThreadId);
}
async createSessionWithContext(params: {
channelId: string;
agentName: string;
workingDirectory: string;
contextQuery: import("../plugins/context/context-provider.js").ContextQuery;
contextOptions?: import("../plugins/context/context-provider.js").ContextOptions;
createThread?: boolean;
}): Promise<{ session: Session; contextResult: import("../plugins/context/context-provider.js").ContextResult | null }> {
return this.sessionFactory.createSessionWithContext(params);
}
```
Remove the old full implementations of these 3 methods from `core.ts`.
- [ ] **Step 3: Build and run tests**
```bash
pnpm build && pnpm test
```
Expected: All tests pass. Callers of `core.handleNewSession()` in `plugins/telegram/commands/new-session.ts`, `core.handleNewChat()`, and `core.createSessionWithContext()` in `plugins/telegram/commands/resume.ts` work unchanged because method signatures are preserved.
- [ ] **Step 4: Commit**
```bash
git add src/core/sessions/session-factory.ts src/core/core.ts
git commit -m "refactor: move handleNewSession, handleNewChat, createSessionWithContext to SessionFactory"
```
---
### Task 5: Clean up and verify final state
**Files:**
- Review: `src/core/core.ts`
- [ ] **Step 1: Verify core.ts line count and remaining methods**
```bash
wc -l src/core/core.ts
```
Expected: ~400 lines. Remaining methods should be:
- Constructor + service getters
- `registerAdapter()`, `start()`, `stop()`
- `handleMessage()` (thin — delegates to sessionFactory.getOrResume)
- `createSession()` (orchestration: factory.create + thread + bridge + persist)
- `adoptSession()` (validation + orchestration)
- `archiveSession()`
- `createBridge()`
- `handleNewSession()`, `handleNewChat()`, `createSessionWithContext()` (thin delegators)
- `getOrResumeSession()` (thin delegator)
- `switchSessionAgent()` (thin delegator)
- [ ] **Step 2: Remove unused imports from core.ts**
Check for imports that were only used by moved code (e.g., `getAgentCapabilities` if only used in switch logic). Remove any dead imports.
- [ ] **Step 3: Run full test suite one final time**
```bash
pnpm build && pnpm test
```
Expected: All tests pass.
- [ ] **Step 4: Final commit**
```bash
git add -A
git commit -m "refactor: clean up core.ts after phase 1 extraction"
```

File diff suppressed because it is too large Load Diff

View File

@ -1,689 +0,0 @@
# Startup UX Improvements Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Improve the CLI experience when interacting with a running daemon — rich status display, interactive menu, instance clarity, attach command, and mode-switching restart.
**Architecture:** Add three new modules (`interactive-menu.ts`, `instance-hint.ts`, `attach.ts`) and modify the default/start/restart commands to use them. TTY detection gates interactive behavior; non-TTY gets info-only output.
**Tech Stack:** Node.js readline (raw mode keypress), `process.stdout.isTTY`, existing `readInstanceInfo()` from `status.ts`, existing daemon functions.
**Spec:** `docs/superpowers/specs/2026-03-31-startup-ux-design.md`
---
### Task 1: Instance hint utility
Shared utility that prints which instance is being used and hints about alternatives.
**Files:**
- Create: `src/cli/instance-hint.ts`
- [ ] **Step 1: Create instance-hint.ts**
```typescript
// src/cli/instance-hint.ts
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { getGlobalRoot } from '../core/instance-context.js'
/**
* Print which instance root is being used.
* If a local .openacp exists in cwd but global is active, show a hint.
*/
export function printInstanceHint(root: string): void {
const globalRoot = getGlobalRoot()
const isGlobal = root === globalRoot
const displayPath = root.replace(os.homedir(), '~')
const label = isGlobal ? 'global' : 'local'
console.log(` Instance: ${displayPath} (${label})`)
// If using global but local exists in cwd, hint
if (isGlobal) {
const localRoot = path.join(process.cwd(), '.openacp')
if (fs.existsSync(localRoot)) {
const localDisplay = localRoot.replace(os.homedir(), '~')
console.log(` \x1b[2mhint: local instance found at ${localDisplay} — use --local to use it\x1b[0m`)
}
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/instance-hint.ts
git commit -m "feat(cli): add instance hint utility for startup clarity"
```
---
### Task 2: Interactive menu utility
TTY-aware keypress menu that shows options and executes on single keypress.
**Files:**
- Create: `src/cli/interactive-menu.ts`
- [ ] **Step 1: Create interactive-menu.ts**
```typescript
// src/cli/interactive-menu.ts
import readline from 'node:readline'
export interface MenuOption {
key: string
label: string
action: () => Promise<void> | void
}
/**
* Show an interactive single-keypress menu (TTY only).
* Returns true if a menu was shown, false if non-TTY.
*/
export function showInteractiveMenu(options: MenuOption[]): Promise<boolean> {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
return Promise.resolve(false)
}
// Print options in two columns
const half = Math.ceil(options.length / 2)
for (let i = 0; i < half; i++) {
const left = options[i]!
const right = options[i + half]
const leftStr = ` \x1b[1m[${left.key}]\x1b[0m ${left.label}`
if (right) {
const rightStr = `\x1b[1m[${right.key}]\x1b[0m ${right.label}`
console.log(`${leftStr.padEnd(34)}${rightStr}`)
} else {
console.log(leftStr)
}
}
console.log('')
return new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, terminal: false })
process.stdin.setRawMode(true)
process.stdin.resume()
const onData = async (buf: Buffer) => {
const ch = buf.toString().toLowerCase()
// Handle Ctrl+C
if (ch === '\x03') {
cleanup()
process.exit(0)
}
const option = options.find(o => o.key === ch)
if (option) {
cleanup()
console.log('')
await option.action()
resolve(true)
}
// Ignore unrecognized keys
}
const cleanup = () => {
process.stdin.removeListener('data', onData)
process.stdin.setRawMode(false)
process.stdin.pause()
rl.close()
}
process.stdin.on('data', onData)
})
}
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/interactive-menu.ts
git commit -m "feat(cli): add interactive keypress menu utility"
```
---
### Task 3: Rich status display for running daemon
Extract a shared function that prints rich daemon status info, used by both the default command and attach.
**Files:**
- Modify: `src/cli/commands/status.ts` — export `formatInstanceStatus()`
- [ ] **Step 1: Add formatInstanceStatus to status.ts**
Add this function after the existing `readInstanceInfo` function in `src/cli/commands/status.ts`:
```typescript
export function formatInstanceStatus(root: string): { info: InstanceInfo; lines: string[] } | null {
const info = readInstanceInfo(root)
if (!info.pid) return null
const displayRoot = root.replace(os.homedir(), '~')
const isGlobal = root === path.join(os.homedir(), '.openacp')
const label = isGlobal ? 'global' : 'local'
const lines: string[] = []
lines.push(` PID: ${info.pid}`)
lines.push(` Instance: ${displayRoot} (${label})`)
lines.push(` Mode: ${info.runMode ?? 'unknown'}`)
if (info.channels.length > 0) lines.push(` Channels: ${info.channels.join(', ')}`)
if (info.apiPort) lines.push(` API: port ${info.apiPort}`)
if (info.tunnelPort) lines.push(` Tunnel: port ${info.tunnelPort}`)
return { info, lines }
}
```
Need to add the `path` import at the top of the file (it already imports `os` and `path`).
- [ ] **Step 2: Commit**
```bash
git add src/cli/commands/status.ts
git commit -m "feat(cli): add formatInstanceStatus for rich status display"
```
---
### Task 4: Rewrite default command with smart daemon detection + interactive menu
The main change: when `openacp` is run and daemon is already running, show rich status + interactive menu instead of an error.
**Files:**
- Modify: `src/cli/commands/default.ts`
- [ ] **Step 1: Rewrite default.ts**
Replace the entire content of `src/cli/commands/default.ts` with:
```typescript
import { checkAndPromptUpdate } from '../version.js'
import { printHelp } from './help.js'
import path from 'node:path'
import os from 'node:os'
import { createInstanceContext, getGlobalRoot } from '../../core/instance-context.js'
import { printInstanceHint } from '../instance-hint.js'
export async function cmdDefault(command: string | undefined, instanceRoot?: string): Promise<void> {
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
const pluginsDataDir = path.join(root, 'plugins', 'data')
const registryPath = path.join(root, 'plugins.json')
const forceForeground = command === '--foreground'
// Reject unknown commands
if (command && !command.startsWith('-')) {
const { suggestMatch } = await import('../suggest.js')
const topLevelCommands = [
'start', 'stop', 'status', 'logs', 'config', 'reset', 'update',
'install', 'uninstall', 'plugins', 'plugin', 'api', 'adopt', 'integrate', 'doctor', 'agents', 'onboard',
'attach',
]
const suggestion = suggestMatch(command, topLevelCommands)
console.error(`Unknown command: ${command}`)
if (suggestion) console.error(`Did you mean: ${suggestion}?`)
printHelp()
process.exit(1)
}
await checkAndPromptUpdate()
const { ConfigManager } = await import('../../core/config/config.js')
const cm = new ConfigManager()
// If no config, run setup first
if (!(await cm.exists())) {
const { SettingsManager } = await import('../../core/plugin/settings-manager.js')
const { PluginRegistry } = await import('../../core/plugin/plugin-registry.js')
const settingsManager = new SettingsManager(pluginsDataDir)
const pluginRegistry = new PluginRegistry(registryPath)
await pluginRegistry.load()
const { runSetup } = await import('../../core/setup/index.js')
const shouldStart = await runSetup(cm, { settingsManager, pluginRegistry })
if (!shouldStart) process.exit(0)
}
await cm.load()
const config = cm.get()
// Check if daemon is already running before trying to start
if (!forceForeground && config.runMode === 'daemon') {
const { isProcessRunning, getPidPath, startDaemon } = await import('../daemon.js')
const pidPath = getPidPath(root)
if (isProcessRunning(pidPath)) {
await showAlreadyRunningMenu(root)
return
}
const result = startDaemon(pidPath, config.logging.logDir, root)
if ('error' in result) {
console.error(result.error)
process.exit(1)
}
printInstanceHint(root)
console.log(`OpenACP daemon started (PID ${result.pid})`)
return
}
const { markRunning } = await import('../daemon.js')
markRunning(root)
printInstanceHint(root)
const { startServer } = await import('../../main.js')
const ctx = createInstanceContext({
id: 'default',
root,
isGlobal: root === getGlobalRoot(),
})
await startServer({ instanceContext: ctx })
}
async function showAlreadyRunningMenu(root: string): Promise<void> {
const { formatInstanceStatus } = await import('./status.js')
console.log('')
console.log('\x1b[1mOpenACP is already running\x1b[0m')
console.log('')
const status = formatInstanceStatus(root)
if (status) {
for (const line of status.lines) {
console.log(line)
}
console.log('')
}
// TTY: interactive menu
const { showInteractiveMenu } = await import('../interactive-menu.js')
const shown = await showInteractiveMenu([
{
key: 'r', label: 'Restart',
action: async () => {
const { cmdRestart } = await import('./restart.js')
await cmdRestart([], root)
},
},
{
key: 'f', label: 'Restart in foreground',
action: async () => {
const { cmdRestart } = await import('./restart.js')
await cmdRestart(['--foreground'], root)
},
},
{
key: 's', label: 'Stop',
action: async () => {
const { cmdStop } = await import('./stop.js')
await cmdStop([], root)
},
},
{
key: 'l', label: 'View logs',
action: async () => {
const { cmdLogs } = await import('./logs.js')
await cmdLogs([])
},
},
{
key: 'q', label: 'Quit',
action: () => { /* exit naturally */ },
},
])
// Non-TTY: print suggestions and exit
if (!shown) {
console.log(' Use: openacp restart | openacp stop | openacp logs')
console.log('')
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/commands/default.ts
git commit -m "feat(cli): smart default command with rich status menu when daemon running"
```
---
### Task 5: Add --foreground and --daemon flags to restart command
**Files:**
- Modify: `src/cli/commands/restart.ts`
- [ ] **Step 1: Rewrite restart.ts**
Replace entire content of `src/cli/commands/restart.ts`:
```typescript
import { wantsHelp } from './helpers.js'
import { printInstanceHint } from '../instance-hint.js'
import path from 'node:path'
import os from 'node:os'
import { createInstanceContext, getGlobalRoot } from '../../core/instance-context.js'
export async function cmdRestart(args: string[] = [], instanceRoot?: string): Promise<void> {
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
if (wantsHelp(args)) {
console.log(`
\x1b[1mopenacp restart\x1b[0m — Restart the background daemon
\x1b[1mUsage:\x1b[0m
openacp restart
openacp restart --foreground Restart in foreground mode
openacp restart --daemon Restart as background daemon
Stops the running daemon (if any) and starts a new one.
\x1b[1mSee also:\x1b[0m
openacp start Start the daemon
openacp stop Stop the daemon
openacp status Check if daemon is running
`)
return
}
const forceForeground = args.includes('--foreground')
const forceDaemon = args.includes('--daemon')
const { stopDaemon, startDaemon, getPidPath, markRunning } = await import('../daemon.js')
const { ConfigManager } = await import('../../core/config/config.js')
const { checkAndPromptUpdate } = await import('../version.js')
await checkAndPromptUpdate()
const pidPath = getPidPath(root)
// Stop existing daemon (ignore errors — it may not be running)
const stopResult = await stopDaemon(pidPath, root)
if (stopResult.stopped) {
console.log(`Stopped daemon (was PID ${stopResult.pid})`)
}
const cm = new ConfigManager()
if (!(await cm.exists())) {
console.error('No config found. Run "openacp" first to set up.')
process.exit(1)
}
await cm.load()
const config = cm.get()
// Determine mode: explicit flag > config
const useForeground = forceForeground || (!forceDaemon && config.runMode !== 'daemon')
if (useForeground) {
markRunning(root)
printInstanceHint(root)
console.log('Starting in foreground mode...')
const { startServer } = await import('../../main.js')
const ctx = createInstanceContext({
id: 'default',
root,
isGlobal: root === getGlobalRoot(),
})
await startServer({ instanceContext: ctx })
} else {
const result = startDaemon(pidPath, config.logging.logDir, root)
if ('error' in result) {
console.error(result.error)
process.exit(1)
}
printInstanceHint(root)
console.log(`OpenACP daemon started (PID ${result.pid})`)
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/commands/restart.ts
git commit -m "feat(cli): add --foreground and --daemon flags to restart command"
```
---
### Task 6: Add instance hint to start command
**Files:**
- Modify: `src/cli/commands/start.ts`
- [ ] **Step 1: Add instance hint to start.ts**
Replace content of `src/cli/commands/start.ts`:
```typescript
import { checkAndPromptUpdate } from '../version.js'
import { wantsHelp } from './helpers.js'
import { printInstanceHint } from '../instance-hint.js'
import path from 'node:path'
import os from 'node:os'
export async function cmdStart(args: string[] = [], instanceRoot?: string): Promise<void> {
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
if (wantsHelp(args)) {
console.log(`
\x1b[1mopenacp start\x1b[0m — Start OpenACP as a background daemon
\x1b[1mUsage:\x1b[0m
openacp start
Starts the server as a background process (daemon mode).
Requires an existing config — run 'openacp' first to set up.
\x1b[1mSee also:\x1b[0m
openacp stop Stop the daemon
openacp restart Restart the daemon
openacp status Check if daemon is running
openacp logs Tail daemon log file
`)
return
}
await checkAndPromptUpdate()
const { startDaemon, getPidPath } = await import('../daemon.js')
const { ConfigManager } = await import('../../core/config/config.js')
const cm = new ConfigManager()
if (await cm.exists()) {
await cm.load()
const config = cm.get()
const result = startDaemon(getPidPath(root), config.logging.logDir, root)
if ('error' in result) {
console.error(result.error)
process.exit(1)
}
printInstanceHint(root)
console.log(`OpenACP daemon started (PID ${result.pid})`)
} else {
console.error('No config found. Run "openacp" first to set up.')
process.exit(1)
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/commands/start.ts
git commit -m "feat(cli): show instance hint on start command"
```
---
### Task 7: Create attach command
**Files:**
- Create: `src/cli/commands/attach.ts`
- Modify: `src/cli/commands/index.ts` — add export
- Modify: `src/cli.ts` — add route
- [ ] **Step 1: Create attach.ts**
```typescript
// src/cli/commands/attach.ts
import { wantsHelp } from './helpers.js'
import path from 'node:path'
import os from 'node:os'
export async function cmdAttach(args: string[] = [], instanceRoot?: string): Promise<void> {
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
if (wantsHelp(args)) {
console.log(`
\x1b[1mopenacp attach\x1b[0m — Attach to a running daemon
\x1b[1mUsage:\x1b[0m
openacp attach
Shows the daemon status and streams log output.
Press Ctrl+C to detach.
\x1b[1mSee also:\x1b[0m
openacp logs Tail daemon log file only
openacp status Show daemon status only
`)
return
}
const { formatInstanceStatus } = await import('./status.js')
const status = formatInstanceStatus(root)
if (!status) {
console.log('OpenACP is not running.')
process.exit(1)
}
console.log('')
console.log(`\x1b[1mOpenACP is running\x1b[0m (PID ${status.info.pid})`)
console.log('')
for (const line of status.lines) {
// Skip PID line since we already show it above
if (!line.includes('PID:')) console.log(line)
}
console.log('')
console.log('--- logs (Ctrl+C to detach) ---')
console.log('')
// Tail logs
const { spawn } = await import('node:child_process')
const { ConfigManager, expandHome } = await import('../../core/config/config.js')
const cm = new ConfigManager()
let logDir = '~/.openacp/logs'
if (await cm.exists()) {
await cm.load()
logDir = cm.get().logging.logDir
}
const logFile = path.join(expandHome(logDir), 'openacp.log')
const tail = spawn('tail', ['-f', '-n', '50', logFile], { stdio: 'inherit' })
tail.on('error', (err: Error) => {
console.error(`Cannot tail log file: ${err.message}`)
process.exit(1)
})
}
```
- [ ] **Step 2: Add export to index.ts**
In `src/cli/commands/index.ts`, add:
```typescript
export { cmdAttach } from './attach.js'
```
- [ ] **Step 3: Add route in cli.ts**
In `src/cli.ts`, add `cmdAttach` to the import and add the route in the commands record:
```typescript
// In import line, add cmdAttach
import {
// ... existing imports ...
cmdAttach,
} from './cli/commands/index.js'
// In commands record, add:
'attach': () => cmdAttach(args, root),
```
- [ ] **Step 4: Commit**
```bash
git add src/cli/commands/attach.ts src/cli/commands/index.ts src/cli.ts
git commit -m "feat(cli): add attach command to connect to running daemon"
```
---
### Task 8: Update help text
**Files:**
- Modify: `src/cli/commands/help.ts`
- [ ] **Step 1: Update help.ts**
In the Server section of `printHelp()`, add the attach command and document new restart flags:
Replace the Server section:
```
\x1b[1mServer:\x1b[0m
openacp Start (mode from config)
openacp start Start as background daemon
openacp stop Stop background daemon
openacp restart Restart background daemon
openacp status Show daemon status
openacp logs Tail daemon log file
openacp --foreground Force foreground mode
```
With:
```
\x1b[1mServer:\x1b[0m
openacp Start (mode from config)
openacp start Start as background daemon
openacp stop Stop background daemon
openacp restart Restart (same mode)
openacp restart --foreground Restart in foreground mode
openacp restart --daemon Restart as background daemon
openacp attach Attach to running daemon
openacp status Show daemon status
openacp logs Tail daemon log file
openacp --foreground Force foreground mode
```
- [ ] **Step 2: Commit**
```bash
git add src/cli/commands/help.ts
git commit -m "docs(cli): update help text with attach command and restart flags"
```
---
### Task 9: Build and manual verification
- [ ] **Step 1: Build the project**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: Clean compilation with no errors
- [ ] **Step 2: Verify new files compile**
Check that `dist/cli/instance-hint.js`, `dist/cli/interactive-menu.js`, and `dist/cli/commands/attach.js` exist.
- [ ] **Step 3: Commit any fixes if needed**
---
### Task 10: Final commit with all changes
- [ ] **Step 1: Verify git status is clean**
Run: `git status`
Expected: All changes committed across tasks 1-9.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,936 +0,0 @@
# Instances CLI & Auth Exchange Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add `openacp instances list/create` CLI subcommands, extend `start --json` output with name/directory, and add `POST /api/v1/auth/exchange` + `GET /api/v1/workspace` API endpoints.
**Architecture:** New `instances.ts` CLI command follows existing command patterns (`cmdStatus`, `cmdStart`). Auth exchange adds one route to existing `auth.ts`. Workspace endpoint is a new route registered in the api-server plugin. All JSON output uses the existing `jsonSuccess`/`jsonError` helpers from `cli/output.ts`.
**Tech Stack:** TypeScript, Node.js, Vitest, Fastify, ESM (`.js` extensions required on all imports)
---
## File Map
**New files:**
- `src/cli/commands/instances.ts` — `instances list` and `instances create` subcommands
- `src/plugins/api-server/routes/workspace.ts` — `GET /api/v1/workspace` route
- `src/core/__tests__/instances-cli.test.ts` — tests for instances list/create logic
- `src/plugins/api-server/__tests__/auth-exchange.test.ts` — tests for POST /exchange
- `src/plugins/api-server/__tests__/workspace-route.test.ts` — tests for GET /workspace
**Modified files:**
- `src/cli/commands/index.ts` — export `cmdInstances`
- `src/cli.ts` — register `instances` in `noInstanceCommands` map (does not require an existing instance root)
- `src/cli/commands/start.ts` — extend `--json` output with `name`, `directory`, `port`
- `src/cli/commands/default.ts` — extend `--json` output after onboarding wizard
- `src/plugins/api-server/routes/auth.ts` — add `POST /exchange` route
- `src/plugins/api-server/index.ts` (the plugin setup file) — register workspace route
---
## Task 1: `instances list` Command
**Files:**
- Create: `src/cli/commands/instances.ts`
- Create: `src/core/__tests__/instances-cli.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// src/core/__tests__/instances-cli.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'
import path from 'node:path'
// We test the pure data-mapping logic extracted from the command
// by mocking readInstanceInfo and InstanceRegistry
vi.mock('../../cli/commands/status.js', () => ({
readInstanceInfo: vi.fn(),
}))
vi.mock('../../core/instance/instance-registry.js', () => ({
InstanceRegistry: vi.fn().mockImplementation(() => ({
load: vi.fn(),
list: vi.fn().mockReturnValue([]),
})),
}))
vi.mock('../../core/instance/instance-context.js', () => ({
getGlobalRoot: vi.fn().mockReturnValue('/Users/user/.openacp'),
}))
import { buildInstanceListEntries } from '../../cli/commands/instances.js'
import { readInstanceInfo } from '../../cli/commands/status.js'
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
describe('buildInstanceListEntries', () => {
beforeEach(() => { vi.clearAllMocks() })
it('returns empty array when no instances registered', async () => {
const mockRegistry = { load: vi.fn(), list: vi.fn().mockReturnValue([]) }
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
const result = await buildInstanceListEntries()
expect(result).toEqual([])
})
it('maps registry entries to InstanceListEntry with correct fields', async () => {
const mockRegistry = {
load: vi.fn(),
list: vi.fn().mockReturnValue([
{ id: 'main', root: '/Users/user/.openacp' },
]),
}
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
vi.mocked(readInstanceInfo).mockReturnValue({
name: 'Main', pid: 1234, apiPort: 21420,
tunnelPort: null, runMode: 'daemon', channels: [],
})
const result = await buildInstanceListEntries()
expect(result).toEqual([{
id: 'main',
name: 'Main',
directory: '/Users/user',
root: '/Users/user/.openacp',
status: 'running',
port: 21420,
}])
})
it('sets status stopped when pid is null', async () => {
const mockRegistry = {
load: vi.fn(),
list: vi.fn().mockReturnValue([{ id: 'dev', root: '/project/.openacp' }]),
}
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
vi.mocked(readInstanceInfo).mockReturnValue({
name: 'Dev', pid: null, apiPort: null,
tunnelPort: null, runMode: null, channels: [],
})
const result = await buildInstanceListEntries()
expect(result[0]!.status).toBe('stopped')
expect(result[0]!.port).toBeNull()
})
it('computes directory as path.dirname(root)', async () => {
const mockRegistry = {
load: vi.fn(),
list: vi.fn().mockReturnValue([
{ id: 'proj', root: '/Users/user/my-project/.openacp' },
]),
}
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
vi.mocked(readInstanceInfo).mockReturnValue({
name: 'Proj', pid: null, apiPort: null,
tunnelPort: null, runMode: null, channels: [],
})
const result = await buildInstanceListEntries()
expect(result[0]!.directory).toBe('/Users/user/my-project')
expect(result[0]!.root).toBe('/Users/user/my-project/.openacp')
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/core/__tests__/instances-cli.test.ts
```
Expected: FAIL — `buildInstanceListEntries` not found
- [ ] **Step 3: Implement `instances list`**
```typescript
// src/cli/commands/instances.ts
import path from 'node:path'
import os from 'node:os'
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
import { getGlobalRoot } from '../../core/instance/instance-context.js'
import { readInstanceInfo } from './status.js'
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
import { wantsHelp } from './helpers.js'
export interface InstanceListEntry {
id: string
name: string | null
directory: string
root: string
status: 'running' | 'stopped'
port: number | null
}
export async function buildInstanceListEntries(): Promise<InstanceListEntry[]> {
const registryPath = path.join(getGlobalRoot(), 'instances.json')
const registry = new InstanceRegistry(registryPath)
await registry.load()
return registry.list().map(entry => {
const info = readInstanceInfo(entry.root)
return {
id: entry.id,
name: info.name,
directory: path.dirname(entry.root),
root: entry.root,
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
port: info.apiPort,
}
})
}
export async function cmdInstances(args: string[] = [], _instanceRoot?: string): Promise<void> {
const sub = args[0]
const subArgs = args.slice(1)
if (!sub || sub === 'list') return cmdInstancesList(subArgs)
if (sub === 'create') return cmdInstancesCreate(subArgs)
if (wantsHelp(args)) {
printInstancesHelp()
return
}
console.error(`Unknown subcommand: instances ${sub}`)
printInstancesHelp()
process.exit(1)
}
function printInstancesHelp(): void {
console.log(`
\x1b[1mopenacp instances\x1b[0m — Manage OpenACP instances
\x1b[1mSubcommands:\x1b[0m
list List all registered instances
create Create or register an instance
\x1b[1mOptions:\x1b[0m
--json Output as JSON
`)
}
async function cmdInstancesList(args: string[]): Promise<void> {
const json = isJsonMode(args)
if (json) await muteForJson()
const entries = await buildInstanceListEntries()
if (json) {
jsonSuccess(entries)
return
}
if (entries.length === 0) {
console.log('No instances registered.')
return
}
console.log('')
console.log(' Status ID Name Directory')
console.log(' ' + '─'.repeat(70))
for (const e of entries) {
const status = e.status === 'running' ? '● running' : '○ stopped'
const port = e.port ? `:${e.port}` : '—'
const dir = e.directory.replace(os.homedir(), '~')
const name = (e.name ?? e.id).padEnd(16)
console.log(` ${status.padEnd(10)} ${e.id.padEnd(16)} ${name} ${dir} ${port}`)
}
console.log('')
}
```
- [ ] **Step 4: Run test to verify it passes**
```bash
pnpm test src/core/__tests__/instances-cli.test.ts
```
Expected: PASS (all 4 tests)
- [ ] **Step 5: Commit**
```bash
git add src/cli/commands/instances.ts src/core/__tests__/instances-cli.test.ts
git commit -m "feat: add instances list command with --json output"
```
---
## Task 2: `instances create` Command
**Files:**
- Modify: `src/cli/commands/instances.ts`
- Modify: `src/core/__tests__/instances-cli.test.ts`
- [ ] **Step 1: Add tests for create**
Add to `src/core/__tests__/instances-cli.test.ts`:
```typescript
import fs from 'node:fs'
import { cmdInstancesCreate } from '../../cli/commands/instances.js'
vi.mock('node:fs')
vi.mock('../../core/config/config.js', () => ({
ConfigManager: vi.fn().mockImplementation(() => ({
exists: vi.fn().mockResolvedValue(false),
})),
}))
describe('cmdInstancesCreate', () => {
beforeEach(() => { vi.clearAllMocks() })
it('errors when --dir is missing', async () => {
const mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
const mockError = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(cmdInstancesCreate([])).rejects.toThrow('exit')
expect(mockError).toHaveBeenCalledWith(expect.stringContaining('--dir'))
mockExit.mockRestore()
mockError.mockRestore()
})
it('errors when .openacp already exists and is registered', async () => {
vi.mocked(fs.existsSync).mockReturnValue(true)
const mockRegistry = {
load: vi.fn(),
getByRoot: vi.fn().mockReturnValue({ id: 'existing', root: '/path/.openacp' }),
}
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
const mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
const mockError = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(cmdInstancesCreate(['--dir', '/path'])).rejects.toThrow('exit')
expect(mockError).toHaveBeenCalledWith(expect.stringContaining('existing'))
mockExit.mockRestore()
mockError.mockRestore()
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
pnpm test src/core/__tests__/instances-cli.test.ts
```
Expected: FAIL — `cmdInstancesCreate` not exported
- [ ] **Step 3: Implement `cmdInstancesCreate`**
Add to `src/cli/commands/instances.ts`:
```typescript
import { generateSlug } from '../../core/instance/instance-context.js'
export async function cmdInstancesCreate(args: string[]): Promise<void> {
const json = isJsonMode(args)
if (json) await muteForJson()
// Parse flags
const dirIdx = args.indexOf('--dir')
const rawDir = dirIdx !== -1 ? args[dirIdx + 1] : undefined
if (!rawDir) {
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, '--dir is required')
console.error('Error: --dir is required')
process.exit(1)
}
const fromIdx = args.indexOf('--from')
const rawFrom = fromIdx !== -1 ? args[fromIdx + 1] : undefined
const nameIdx = args.indexOf('--name')
const instanceName = nameIdx !== -1 ? args[nameIdx + 1] : undefined
const agentIdx = args.indexOf('--agent')
const agent = agentIdx !== -1 ? args[agentIdx + 1] : undefined
const noInteractive = args.includes('--no-interactive')
// Resolve absolute paths
const resolvedDir = path.resolve(rawDir!.replace(/^~/, os.homedir()))
const instanceRoot = path.join(resolvedDir, '.openacp')
const registryPath = path.join(getGlobalRoot(), 'instances.json')
const registry = new InstanceRegistry(registryPath)
await registry.load()
// Case: .openacp already exists
if (fs.existsSync(instanceRoot)) {
const existing = registry.getByRoot(instanceRoot)
if (existing) {
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, `Instance already exists at ${resolvedDir} (id: ${existing.id})`)
console.error(`Error: Instance already exists at ${resolvedDir} (id: ${existing.id})`)
process.exit(1)
}
// .openacp exists but not registered — register it
const config = JSON.parse(fs.readFileSync(path.join(instanceRoot, 'config.json'), 'utf-8'))
const name = config.instanceName ?? path.basename(resolvedDir)
const baseId = generateSlug(name)
const id = registry.uniqueId(baseId)
registry.register(id, instanceRoot)
await registry.save()
return outputInstance(json, { id, root: instanceRoot })
}
// Case: create new
const name = instanceName ?? `openacp-${registry.list().length + 1}`
const baseId = generateSlug(name)
const id = registry.uniqueId(baseId)
fs.mkdirSync(instanceRoot, { recursive: true })
if (rawFrom) {
// Clone from existing
const fromRoot = path.join(path.resolve(rawFrom.replace(/^~/, os.homedir())), '.openacp')
if (!fs.existsSync(path.join(fromRoot, 'config.json'))) {
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, `No OpenACP instance found at ${rawFrom}`)
console.error(`Error: No OpenACP instance found at ${rawFrom}`)
process.exit(1)
}
const { cloneInstance } = await import('../../core/setup/clone.js')
await cloneInstance(fromRoot, instanceRoot, { instanceName: name })
} else if (noInteractive) {
// Minimal config
const config: Record<string, unknown> = { instanceName: name, runMode: 'daemon' }
if (agent) config.defaultAgent = agent
fs.writeFileSync(path.join(instanceRoot, 'config.json'), JSON.stringify(config, null, 2))
fs.writeFileSync(path.join(instanceRoot, 'plugins.json'), JSON.stringify({ version: 1, installed: {} }, null, 2))
} else {
// Run setup wizard (interactive)
const { runSetup } = await import('../../core/setup/wizard.js')
await runSetup({ instanceRoot, instanceName: name })
}
registry.register(id, instanceRoot)
await registry.save()
return outputInstance(json, { id, root: instanceRoot })
}
async function outputInstance(json: boolean, { id, root }: { id: string; root: string }): Promise<void> {
const info = readInstanceInfo(root)
const entry: InstanceListEntry = {
id,
name: info.name,
directory: path.dirname(root),
root,
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
port: info.apiPort,
}
if (json) {
jsonSuccess(entry)
return
}
console.log(`Instance created: ${info.name ?? id} at ${path.dirname(root)}`)
}
```
> **Note:** `generateSlug` is exported from `instance-context.ts`. `cloneInstance` in `core/setup/clone.js` may be a different path — check the actual clone logic location in the multi-instance implementation before using this import.
- [ ] **Step 4: Run tests**
```bash
pnpm test src/core/__tests__/instances-cli.test.ts
```
Expected: PASS (all tests)
- [ ] **Step 5: Commit**
```bash
git add src/cli/commands/instances.ts src/core/__tests__/instances-cli.test.ts
git commit -m "feat: add instances create command"
```
---
## Task 3: Register `instances` in CLI
**Files:**
- Modify: `src/cli/commands/index.ts`
- Modify: `src/cli.ts`
- [ ] **Step 1: Export from index.ts**
In `src/cli/commands/index.ts`, add:
```typescript
export { cmdInstances } from './instances.js'
```
Add it with the other command exports (alphabetical order near `cmdIntegrate` or `cmdInstall`).
- [ ] **Step 2: Register in cli.ts**
In `src/cli.ts`, add `cmdInstances` to the import from `./cli/commands/index.js`:
```typescript
import {
// ... existing imports ...
cmdInstances,
} from './cli/commands/index.js'
```
In the `noInstanceCommands` object (not `instanceCommands`), add:
```typescript
'instances': async () => cmdInstances(args),
```
`instances` must be in `noInstanceCommands` because it does not require an existing instance root — it reads the global `~/.openacp/instances.json` registry directly. Adding it to `instanceCommands` would cause `resolveRoot()` to prompt the user to select an instance before listing, which breaks the command.
- [ ] **Step 3: Verify registration works**
```bash
pnpm build && node dist/cli.js instances list
```
Expected: Either table output (if instances registered) or "No instances registered."
```bash
node dist/cli.js instances list --json
```
Expected: `{ "success": true, "data": [...] }`
- [ ] **Step 4: Commit**
```bash
git add src/cli/commands/index.ts src/cli.ts
git commit -m "feat: register instances subcommand in CLI"
```
---
## Task 4: Extend `start --json` Output
**Files:**
- Modify: `src/cli/commands/start.ts`
- Modify: `src/cli/commands/default.ts`
- [ ] **Step 1: Extend start.ts**
In `src/cli/commands/start.ts`, find the `jsonSuccess` call:
```typescript
// Before (line ~50)
if (json) jsonSuccess({ pid: result.pid, instanceId: path.basename(root), dir: root })
```
Replace with:
```typescript
if (json) {
// Read instance name and real id from registry
let name: string | null = null
let instanceId: string = path.basename(root)
try {
const { ConfigManager } = await import('../../core/config/config.js')
const cm = new ConfigManager(path.join(root, 'config.json'))
await cm.load()
name = cm.get().instanceName ?? null
} catch {}
try {
const { getGlobalRoot } = await import('../../core/instance/instance-context.js')
const { InstanceRegistry } = await import('../../core/instance/instance-registry.js')
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
await reg.load()
const entry = reg.getByRoot(root)
if (entry) instanceId = entry.id
} catch {}
// Read port (may not be written yet, that's ok)
let port: number | null = null
try {
port = parseInt(fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()) || null
} catch {}
jsonSuccess({
pid: result.pid,
instanceId,
name,
directory: path.dirname(root),
dir: root, // keep for backward compat
port,
})
}
```
Add `import fs from 'node:fs'` if not already present.
- [ ] **Step 2: Find equivalent output in default.ts**
In `src/cli/commands/default.ts`, search for any `jsonSuccess` call that outputs `pid`/`instanceId`. Apply the same extended fields. If the default command starts the server inline (not via `cmdStart`), locate the exact jsonSuccess call and extend it identically.
- [ ] **Step 3: Verify extended output**
```bash
pnpm build
# Start a test instance and check output:
node dist/cli.js start --json 2>/dev/null | node -e "const d=require('fs').readFileSync('/dev/stdin','utf-8'); const j=JSON.parse(d.trim()); console.log(Object.keys(j.data))"
```
Expected output includes: `pid`, `instanceId`, `name`, `directory`, `dir`, `port`
- [ ] **Step 4: Commit**
```bash
git add src/cli/commands/start.ts src/cli/commands/default.ts
git commit -m "feat: extend start --json output with name, directory, port"
```
---
## Task 5: `POST /api/v1/auth/exchange` Endpoint
**Files:**
- Modify: `src/plugins/api-server/routes/auth.ts`
- Modify: `src/plugins/api-server/auth/token-store.ts` (if `exchangeCode` not already implemented)
- Create: `src/plugins/api-server/__tests__/auth-exchange.test.ts`
> **Check first (two things):**
> 1. Open `src/plugins/api-server/index.ts`. There is likely already a `registerPlugin` call for `POST /exchange` registered with `{ auth: false }` — if so, the route registration boilerplate is done. Verify it calls `tokenStore.exchangeCode()`.
> 2. Open `src/plugins/api-server/auth/token-store.ts` to confirm whether `exchangeCode()` is already defined. If `createCode()` is there but `exchangeCode()` is not, add it in this task. If both exist, skip Step 3 below.
- [ ] **Step 1: Write the failing test**
```typescript
// src/plugins/api-server/__tests__/auth-exchange.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'
import Fastify from 'fastify'
import { authRoutes } from '../routes/auth.js'
function makeTokenStore() {
const codes = new Map<string, { tokenParams: any; expiresAt: string; used: boolean }>()
return {
createCode: vi.fn((params: any) => {
const code = 'test-code-123'
codes.set(code, {
tokenParams: params,
expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
used: false,
})
return { code, expiresAt: codes.get(code)!.expiresAt }
}),
exchangeCode: vi.fn((code: string) => {
const entry = codes.get(code)
if (!entry) throw new Error('Invalid code')
if (new Date(entry.expiresAt) < new Date()) throw new Error('Code expired')
if (entry.used) throw new Error('Code already used')
entry.used = true
return entry.tokenParams
}),
create: vi.fn((params: any) => ({
id: 'tok_test',
name: params.name,
role: params.role,
scopes: params.scopes,
createdAt: new Date().toISOString(),
refreshDeadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
revoked: false,
})),
get: vi.fn(),
revoke: vi.fn(),
list: vi.fn().mockReturnValue([]),
listCodes: vi.fn().mockReturnValue([]),
revokeCode: vi.fn(),
updateLastUsed: vi.fn(),
}
}
async function buildApp(tokenStore: ReturnType<typeof makeTokenStore>) {
const app = Fastify()
app.decorateRequest('auth', null, [])
app.addHook('onRequest', async (req) => {
(req as any).auth = { type: 'secret', role: 'admin', scopes: ['*'] }
})
await app.register(authRoutes, { tokenStore, getJwtSecret: () => 'test-secret' })
await app.ready()
return app
}
describe('POST /exchange', () => {
let tokenStore: ReturnType<typeof makeTokenStore>
let app: Awaited<ReturnType<typeof buildApp>>
beforeEach(async () => {
tokenStore = makeTokenStore()
app = await buildApp(tokenStore)
})
it('returns JWT on valid code', async () => {
// First create a code
tokenStore.createCode({ role: 'admin', name: 'test', expire: '24h' })
const res = await app.inject({
method: 'POST',
url: '/exchange',
payload: { code: 'test-code-123' },
})
expect(res.statusCode).toBe(200)
const body = JSON.parse(res.body)
expect(body).toHaveProperty('accessToken')
expect(body).toHaveProperty('tokenId')
expect(body).toHaveProperty('expiresAt')
expect(body).toHaveProperty('refreshDeadline')
})
it('returns 401 for invalid code', async () => {
const res = await app.inject({
method: 'POST',
url: '/exchange',
payload: { code: 'nonexistent' },
})
expect(res.statusCode).toBe(401)
})
it('returns 401 for already-used code', async () => {
tokenStore.createCode({ role: 'admin', name: 'test', expire: '24h' })
tokenStore.exchangeCode('test-code-123') // use it once
const res = await app.inject({
method: 'POST',
url: '/exchange',
payload: { code: 'test-code-123' },
})
expect(res.statusCode).toBe(401)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
pnpm test src/plugins/api-server/__tests__/auth-exchange.test.ts
```
Expected: FAIL — `POST /exchange` not found (404)
- [ ] **Step 3: Add `exchangeCode` to token store**
Open `src/plugins/api-server/auth/token-store.ts`. Check existing `createCode` implementation. Add `exchangeCode`:
```typescript
// In TokenStore class, add after createCode():
exchangeCode(code: string): CreateTokenOpts {
const entry = this.codes.get(code)
if (!entry) throw new Error('Invalid code')
if (new Date(entry.expiresAt) < new Date()) {
this.codes.delete(code)
throw new Error('Code expired')
}
if (entry.used) throw new Error('Code already used')
entry.used = true
return entry.tokenParams
}
```
> **Note:** The `codes` map and its entry type may already be defined. Adapt to match the actual type. If `TokenStore` is an interface rather than a class, add `exchangeCode` to both the interface and the implementation.
- [ ] **Step 4: Add `POST /exchange` route to auth.ts (if not already present in index.ts)**
If the skeleton route in `index.ts` is incomplete, or auth.ts is the right place for the route body, add the implementation:
```typescript
// POST /exchange — exchange one-time code for JWT (no auth required)
// This route must be registered at the plugin level with { auth: false }
// (via the third argument to registerPlugin in index.ts) — NOT via route-level config.
app.post('/exchange', async (request, reply) => {
const body = z.object({ code: z.string() }).parse(request.body)
let tokenParams: any
try {
tokenParams = tokenStore.exchangeCode(body.code)
} catch (err: any) {
throw new AuthError('UNAUTHORIZED', err.message ?? 'Invalid code')
}
// Generate JWT using exchanged token params (same as POST /tokens)
const stored = tokenStore.create(tokenParams)
const durationMs = parseDuration(tokenParams.expire)
const rfd = new Date(stored.refreshDeadline).getTime() / 1000
const accessToken = signToken(
{ sub: stored.id, role: stored.role, scopes: stored.scopes, rfd },
getJwtSecret(),
tokenParams.expire,
)
const expiresAt = new Date(Date.now() + durationMs).toISOString()
return reply.send({
accessToken,
tokenId: stored.id,
expiresAt,
refreshDeadline: stored.refreshDeadline,
})
})
```
Add `import { z } from 'zod'` at the top if not already present.
> **Auth bypass pattern:** The auth preHandler checks route/plugin registration options, not `request.routeOptions.config`. The correct way to mark a route group as unauthenticated is to pass `{ auth: false }` as the **third argument** to `registerPlugin(prefix, handler, { auth: false })` in `index.ts`. Do NOT use `{ config: { skipAuth: true } }` on individual route definitions — look at how the health or public routes bypass auth to confirm the exact call pattern used in this codebase.
- [ ] **Step 5: Run tests**
```bash
pnpm test src/plugins/api-server/__tests__/auth-exchange.test.ts
```
Expected: PASS (all 3 tests)
- [ ] **Step 6: Commit**
```bash
git add src/plugins/api-server/routes/auth.ts src/plugins/api-server/auth/token-store.ts src/plugins/api-server/__tests__/auth-exchange.test.ts
git commit -m "feat: add POST /auth/exchange for one-time code to JWT"
```
---
## Task 6: `GET /api/v1/workspace` Endpoint
**Files:**
- Create: `src/plugins/api-server/routes/workspace.ts`
- Create: `src/plugins/api-server/__tests__/workspace-route.test.ts`
- Modify: `src/plugins/api-server/index.ts` (the plugin setup file — check exact filename)
- [ ] **Step 1: Write the failing test**
```typescript
// src/plugins/api-server/__tests__/workspace-route.test.ts
import { describe, it, expect } from 'vitest'
import Fastify from 'fastify'
import { workspaceRoute } from '../routes/workspace.js'
async function buildApp(opts: { id: string; name: string; directory: string; version: string }) {
const app = Fastify()
app.decorateRequest('auth', null, [])
app.addHook('onRequest', async (req) => {
(req as any).auth = { type: 'jwt', role: 'admin', scopes: ['system:health'] }
})
await app.register(workspaceRoute, opts)
await app.ready()
return app
}
describe('GET /workspace', () => {
it('returns workspace identity info', async () => {
const app = await buildApp({
id: 'main',
name: 'Main',
directory: '/Users/user',
version: '2026.401.1',
})
const res = await app.inject({ method: 'GET', url: '/workspace' })
expect(res.statusCode).toBe(200)
const body = JSON.parse(res.body)
expect(body).toEqual({
id: 'main',
name: 'Main',
directory: '/Users/user',
version: '2026.401.1',
})
})
it('requires authentication', async () => {
const app = Fastify()
app.decorateRequest('auth', null, [])
app.addHook('onRequest', async (req) => {
// No auth set — simulate unauthenticated request
(req as any).auth = null
})
await app.register(workspaceRoute, {
id: 'main', name: 'Main', directory: '/Users/user', version: '1.0',
})
await app.ready()
// Route should exist and return data when auth is present
// Authentication enforcement is handled by the preHandler in the plugin setup, not the route itself
const res = await app.inject({ method: 'GET', url: '/workspace' })
// With no auth preHandler in this test, it returns 200 (auth is enforced at plugin level)
expect(res.statusCode).toBe(200)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
pnpm test src/plugins/api-server/__tests__/workspace-route.test.ts
```
Expected: FAIL — module not found
- [ ] **Step 3: Implement workspace route**
```typescript
// src/plugins/api-server/routes/workspace.ts
import type { FastifyInstance } from 'fastify'
import path from 'node:path'
export interface WorkspaceRouteOpts {
id: string
name: string
directory: string
version: string
}
export async function workspaceRoute(
app: FastifyInstance,
opts: WorkspaceRouteOpts,
): Promise<void> {
app.get('/workspace', async () => ({
id: opts.id,
name: opts.name,
directory: opts.directory,
version: opts.version,
}))
}
```
- [ ] **Step 4: Register in api-server plugin setup**
Find the api-server plugin setup file (likely `src/plugins/api-server/index.ts`). Locate where other routes are registered (e.g., where `authRoutes` is registered). Add:
```typescript
import { workspaceRoute } from './routes/workspace.js'
import path from 'node:path'
// In the setup function, after other route registrations:
const instanceRoot = ctx.paths.root // or however the plugin accesses instanceRoot
const version = /* get from package.json or config */ '0.0.0'
let workspaceId = 'main'
let workspaceName = 'Main'
let workspaceDir = path.dirname(instanceRoot)
try {
const { InstanceRegistry } = await import('../../core/instance/instance-registry.js')
const { getGlobalRoot } = await import('../../core/instance/instance-context.js')
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
await reg.load()
const entry = reg.getByRoot(instanceRoot)
if (entry) workspaceId = entry.id
} catch {}
try {
const config = JSON.parse(fs.readFileSync(path.join(instanceRoot, 'config.json'), 'utf-8'))
workspaceName = config.instanceName ?? workspaceName
} catch {}
apiServer.registerPlugin('/api/v1', async (pluginApp) => {
await pluginApp.register(workspaceRoute, {
id: workspaceId,
name: workspaceName,
directory: workspaceDir,
version,
})
}, { auth: true })
```
> **Note:** The exact way `instanceRoot` and config are accessed in the plugin context may differ. Look at how other routes in the same file access instance data and follow the same pattern. The `version` should come from `package.json` — look for how other parts of the codebase read it.
- [ ] **Step 5: Run tests**
```bash
pnpm test src/plugins/api-server/__tests__/workspace-route.test.ts
```
Expected: PASS
```bash
pnpm build && pnpm test
```
Expected: All tests pass, no TypeScript errors
- [ ] **Step 6: Commit**
```bash
git add src/plugins/api-server/routes/workspace.ts src/plugins/api-server/__tests__/workspace-route.test.ts src/plugins/api-server/index.ts
git commit -m "feat: add GET /api/v1/workspace endpoint"
```
---
## Self-Review Checklist
After all tasks are complete:
- [ ] `openacp instances list --json` outputs correct schema (`id`, `name`, `directory`, `root`, `status`, `port`)
- [ ] `openacp instances create --dir /path --no-interactive --json` creates instance and returns JSON
- [ ] `openacp instances create --dir /path --from /existing --json` clones and returns JSON
- [ ] `openacp start --json` output includes `name`, `directory`, `port` in addition to existing fields
- [ ] `POST /api/v1/auth/exchange` returns JWT on valid code, 401 on invalid/expired/used
- [ ] `GET /api/v1/workspace` returns `{id, name, directory, version}` with authentication
- [ ] `pnpm test` passes with no failures
- [ ] `pnpm build` compiles with no TypeScript errors

View File

@ -1,604 +0,0 @@
# Menu Button & Command Dispatch Fix — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix all broken/degraded menu buttons and slash commands so they use Telegram-specific rich UI handlers instead of generic core handlers.
**Architecture:** Add an intercept map (`TELEGRAM_OVERRIDES`) that routes 6 commands to Telegram-specific handlers before they reach `CommandRegistry`. Fix the `m:` handler's `callback` case to dispatch Settings and New Session. Add a button-driven New Session flow (`ns:` prefix) that only delegates to AI for custom workspace input.
**Tech Stack:** TypeScript, grammY (Telegram Bot Framework), Vitest
**Spec:** `docs/superpowers/specs/2026-04-02-menu-button-fix-design.md`
---
## File Map
| File | Responsibility | Change type |
|------|---------------|-------------|
| `src/plugins/telegram/commands/index.ts` | Callback routing hub — broad `m:` handler, exports | Modify |
| `src/plugins/telegram/commands/telegram-overrides.ts` | Intercept map: command name → Telegram handler | Create |
| `src/plugins/telegram/commands/new-session.ts` | New Session button flow (`ns:` prefix callbacks) | Modify |
| `src/plugins/telegram/commands/session.ts` | Add `m:topics` callback handler | Modify |
| `src/plugins/telegram/adapter.ts` | Intercept slash commands before `registry.execute()` | Modify |
| `src/core/menu/core-items.ts` | Change New Session action type | Modify |
---
## Task 1: Create Telegram Overrides Map
**Files:**
- Create: `src/plugins/telegram/commands/telegram-overrides.ts`
This is a simple lookup table. No dependencies on adapter.ts — avoids circular imports.
- [ ] **Step 1: Create the intercept map file**
```typescript
// src/plugins/telegram/commands/telegram-overrides.ts
import type { Context } from 'grammy'
import type { OpenACPCore } from '../../../core/index.js'
import { handleAgents } from './agents.js'
import { handleTopics } from './session.js'
import { handleDoctor } from './doctor.js'
import { handleUpdate, handleRestart } from './admin.js'
import { handleHelp } from './menu.js'
/**
* Commands that should be intercepted and handled by Telegram-specific
* handlers instead of going through CommandRegistry core handlers.
*
* These handlers use grammY Context for rich UI (inline keyboards,
* message editing, pagination) that CommandResponse cannot express.
*/
export const TELEGRAM_OVERRIDES: Record<
string,
(ctx: Context, core: OpenACPCore) => Promise<void>
> = {
agents: (ctx, core) => handleAgents(ctx, core),
sessions: (ctx, core) => handleTopics(ctx, core),
doctor: (ctx) => handleDoctor(ctx),
update: (ctx, core) => handleUpdate(ctx, core),
restart: (ctx, core) => handleRestart(ctx, core),
help: (ctx) => handleHelp(ctx),
}
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/commands/telegram-overrides.ts
git commit -m "feat: add Telegram command intercept map"
```
---
## Task 2: Intercept Slash Commands in Adapter
**Files:**
- Modify: `src/plugins/telegram/adapter.ts` (lines 322-394, the `bot.on("message:text")` handler)
Insert the intercept check after extracting `commandName` (line 344) but before `registry.execute()` (line 360).
- [ ] **Step 1: Add import at top of adapter.ts**
Add after the existing imports from `./commands/index.js`:
```typescript
import { TELEGRAM_OVERRIDES } from './commands/telegram-overrides.js'
```
- [ ] **Step 2: Add intercept check in the slash command handler**
In the `bot.on("message:text")` handler, after line 346 (`if (!def) return next();`), add:
```typescript
// Telegram-specific override — use rich handler instead of core CommandRegistry
const telegramOverride = TELEGRAM_OVERRIDES[commandName]
if (telegramOverride) {
try {
await telegramOverride(ctx, this.core as OpenACPCore)
} catch (err) {
await ctx.reply(`⚠️ Command failed: ${String(err)}`)
}
return
}
```
This goes between line 346 (`if (!def) return next()`) and line 348 (`const chatId = ctx.chat.id`).
- [ ] **Step 3: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 4: Commit**
```bash
git add src/plugins/telegram/adapter.ts src/plugins/telegram/commands/telegram-overrides.ts
git commit -m "feat: intercept slash commands for Telegram-specific handlers
/agents, /sessions, /doctor, /update, /restart, /help now use
rich Telegram handlers with inline keyboards instead of generic
CommandRegistry core responses."
```
---
## Task 3: Fix `m:` Handler — Command Type Intercept
**Files:**
- Modify: `src/plugins/telegram/commands/index.ts` (the broad `m:` handler, lines 67-134)
The `command` case currently dispatches everything through `CommandRegistry`. Add intercept check.
- [ ] **Step 1: Add import for TELEGRAM_OVERRIDES**
Add at top of `index.ts`:
```typescript
import { TELEGRAM_OVERRIDES } from './telegram-overrides.js'
```
- [ ] **Step 2: Replace the `command` case in the broad `m:` handler**
Replace lines 82-114 (the entire `case 'command': { ... break }` block):
```typescript
case 'command': {
// Check Telegram-specific override first
const cmdName = item.action.command.replace(/^\//, '').split(' ')[0]
const telegramOverride = TELEGRAM_OVERRIDES[cmdName]
if (telegramOverride) {
try {
await telegramOverride(ctx, core)
} catch (err) {
await ctx.reply(`⚠️ Command failed: ${String(err)}`).catch(() => {})
}
break
}
// Fallback: dispatch through CommandRegistry for commands without overrides
if (!registry) return
const response = await registry.execute(item.action.command, {
raw: '',
channelId: 'telegram',
userId: String(ctx.from.id),
sessionId: null,
reply: async () => {},
})
if (response.type !== 'delegated' && response.type !== 'silent') {
if (response.type === 'text') {
await ctx.reply(response.text, { parse_mode: 'HTML' }).catch(() => {})
} else if (response.type === 'error') {
await ctx.reply(`⚠️ ${response.message}`).catch(() => {})
} else if (response.type === 'list') {
const lines = response.items.map((i: { label: string; detail?: string }) => `• ${i.label}${i.detail ? ` — ${i.detail}` : ''}`).join('\n')
await ctx.reply(`${response.title}\n${lines}`, { parse_mode: 'HTML' }).catch(() => {})
} else if (response.type === 'menu') {
const { InlineKeyboard } = await import('grammy')
const kb = new InlineKeyboard()
for (const opt of response.options) {
kb.text(opt.label, `c/${opt.command}`).row()
}
await ctx.reply(response.title, { parse_mode: 'HTML', reply_markup: kb }).catch(() => {})
} else if (response.type === 'confirm') {
const { InlineKeyboard } = await import('grammy')
const kb = new InlineKeyboard()
.text('✅ Yes', `c/${response.onYes}`)
.text('❌ No', `c/${response.onNo}`)
await ctx.reply(response.question, { reply_markup: kb }).catch(() => {})
}
}
break
}
```
- [ ] **Step 3: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 4: Commit**
```bash
git add src/plugins/telegram/commands/index.ts
git commit -m "feat: intercept menu button commands for Telegram handlers
Menu buttons for Agents, Sessions, Doctor, Update, Restart, Help
now use rich Telegram handlers instead of generic core responses."
```
---
## Task 4: Fix `m:` Handler — Callback Type (Settings)
**Files:**
- Modify: `src/plugins/telegram/commands/index.ts` (the `callback` case, line 130-132)
- [ ] **Step 1: Replace the `callback` case**
Replace lines 130-132:
```typescript
case 'callback':
// Pass through to specific callback handlers
break
```
With:
```typescript
case 'callback': {
const cbData = item.action.callbackData
if (cbData === 's:settings') {
await handleSettings(ctx, core)
}
// ns: callbacks handled in Task 6 (New Session flow)
break
}
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/commands/index.ts
git commit -m "fix: Settings menu button now opens settings keyboard
The callback action type was silently doing nothing (break).
Now dispatches s:settings to handleSettings directly."
```
---
## Task 5: Fix `m:topics` Refresh Button
**Files:**
- Modify: `src/plugins/telegram/commands/session.ts` (inside `setupSessionCallbacks`)
The Refresh button in the sessions list sends `m:topics` which reaches the broad `m:` handler → `menuRegistry.getItem("topics")` → undefined → nothing. Fix by adding a specific handler in `setupSessionCallbacks` which runs BEFORE the broad handler.
- [ ] **Step 1: Add `m:topics` callback handler in `setupSessionCallbacks`**
In `session.ts`, inside `setupSessionCallbacks()`, add after the existing `bot.callbackQuery(/^m:cleanup/, ...)` handler (after line 355):
```typescript
// Refresh sessions list (button created by handleTopics)
bot.callbackQuery('m:topics', async (ctx) => {
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
await handleTopics(ctx, core)
})
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/commands/session.ts
git commit -m "fix: Refresh button in sessions list now works
m:topics callback was falling through to broad m: handler which
couldn't find a menu item for 'topics'. Now handled directly by
setupSessionCallbacks before the broad handler."
```
---
## Task 6: New Session Button Flow
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts` — add `setupNewSessionCallbacks()` and `showAgentPicker()`
- Modify: `src/plugins/telegram/commands/index.ts` — register `ns:` callbacks, update `callback` case
- Modify: `src/core/menu/core-items.ts` — change New Session action type
### Step 1: Add New Session button flow to new-session.ts
- [ ] **Step 1a: Add the workspace cache and agent picker function**
Add at the bottom of `new-session.ts`, before the final export:
```typescript
// --- New Session button flow (ns: prefix) ---
/** Workspace cache for callback data — avoids Telegram's 64-byte callback limit */
const workspaceCache = new Map<number, { agentKey: string; workspace: string }>()
let nextWsId = 0
export async function showAgentPicker(ctx: Context, core: OpenACPCore, chatId: number): Promise<void> {
const catalog = core.agentCatalog
const installed = catalog.getAvailable().filter((i) => i.installed)
if (installed.length === 0) {
await ctx.reply('No agents installed. Use /install to add one.', { parse_mode: 'HTML' }).catch(() => {})
return
}
// Single agent → skip picker, go to workspace
if (installed.length === 1) {
await showWorkspacePicker(ctx, core, chatId, installed[0].key)
return
}
const kb = new InlineKeyboard()
for (let i = 0; i < installed.length; i += 2) {
const row = installed.slice(i, i + 2)
for (const agent of row) {
kb.text(agent.name, `ns:agent:${agent.key}`)
}
kb.row()
}
await ctx.reply('<b>🆕 New Session</b>\nSelect an agent:', {
parse_mode: 'HTML',
reply_markup: kb,
}).catch(() => {})
}
async function showWorkspacePicker(ctx: Context, core: OpenACPCore, chatId: number, agentKey: string): Promise<void> {
const records = core.sessionManager.listRecords()
const recentWorkspaces = [...new Set(records.map((r: any) => r.workingDir).filter(Boolean))]
.slice(0, 5)
const config = core.configManager.get()
const baseDir = config.workspace.baseDir
// Ensure baseDir is always an option
const workspaces = recentWorkspaces.includes(baseDir)
? recentWorkspaces
: [baseDir, ...recentWorkspaces].slice(0, 5)
const kb = new InlineKeyboard()
for (const ws of workspaces) {
const id = nextWsId++
workspaceCache.set(id, { agentKey, workspace: ws })
// Show shortened path for display
const label = ws.startsWith('/Users/') ? '~/' + ws.split('/').slice(3).join('/') : ws
kb.text(`📁 ${label}`, `ns:ws:${id}`).row()
}
// Custom path → delegate to AI
const customId = nextWsId++
workspaceCache.set(customId, { agentKey, workspace: '' }) // empty = custom
kb.text('📁 Custom path...', `ns:custom:${agentKey}`).row()
const agentLabel = escapeHtml(agentKey)
await ctx.reply(`<b>🆕 New Session</b>\nAgent: <code>${agentLabel}</code>\n\nSelect workspace:`, {
parse_mode: 'HTML',
reply_markup: kb,
}).catch(() => {})
}
export function setupNewSessionCallbacks(
bot: Bot,
core: OpenACPCore,
chatId: number,
getAssistantSession?: () => { topicId: number; enqueuePrompt: (p: string) => Promise<void> } | undefined,
): void {
// Agent picker (also triggered from m: handler callback case)
bot.callbackQuery('ns:start', async (ctx) => {
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
await showAgentPicker(ctx, core, chatId)
})
bot.callbackQuery(/^ns:agent:/, async (ctx) => {
const agentKey = ctx.callbackQuery.data.replace('ns:agent:', '')
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
await showWorkspacePicker(ctx, core, chatId, agentKey)
})
bot.callbackQuery(/^ns:ws:/, async (ctx) => {
const id = parseInt(ctx.callbackQuery.data.replace('ns:ws:', ''), 10)
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
const entry = workspaceCache.get(id)
if (!entry) {
await ctx.reply('⚠️ Session expired. Please try again via /menu.').catch(() => {})
return
}
workspaceCache.delete(id)
await createSessionDirect(ctx, core, chatId, entry.agentKey, entry.workspace)
})
bot.callbackQuery(/^ns:custom:/, async (ctx) => {
const agentKey = ctx.callbackQuery.data.replace('ns:custom:', '')
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
const assistant = getAssistantSession?.()
if (assistant) {
await assistant.enqueuePrompt(
`User wants to create a new session with agent "${agentKey}". Ask them for the workspace (project directory) path, then create the session.`
)
} else {
await ctx.reply(
`Usage: <code>/new ${escapeHtml(agentKey)} &lt;workspace-path&gt;</code>`,
{ parse_mode: 'HTML' },
).catch(() => {})
}
})
}
```
- [ ] **Step 1b: Add `InlineKeyboard` to imports**
The top of `new-session.ts` has `import type { Bot, Context } from "grammy"` (line 1). Change it to:
```typescript
import type { Bot, Context } from "grammy";
import { InlineKeyboard } from "grammy";
```
Remove the `import { InlineKeyboard } from 'grammy'` line from inside the new code block added in Step 1a (it's a top-level import now).
- [ ] **Step 1c: Export `showAgentPicker` and `setupNewSessionCallbacks` from the file**
Both are already exported via `export async function` and `export function` in the code above. No additional change needed.
### Step 2: Register ns: callbacks in index.ts
- [ ] **Step 2a: Add imports in index.ts**
Add to the imports from `./new-session.js`:
```typescript
import { handleNew, handleNewChat, createSessionDirect, showAgentPicker, setupNewSessionCallbacks } from './new-session.js'
```
(Replace the existing import line for `new-session.js`.)
- [ ] **Step 2b: Register ns: callbacks in setupAllCallbacks**
Add after the `na:` handler (line 62) and before the `ar:` handler (line 65):
```typescript
// New Session button flow — must be before broad m: handler
setupNewSessionCallbacks(bot, core, chatId, getAssistantSession);
```
- [ ] **Step 2c: Update the `callback` case to handle ns:start**
Update the `callback` case (from Task 4) to also handle `ns:`:
```typescript
case 'callback': {
const cbData = item.action.callbackData
if (cbData === 's:settings') {
await handleSettings(ctx, core)
} else if (cbData === 'ns:start') {
await showAgentPicker(ctx, core, chatId)
}
break
}
```
### Step 3: Update core menu item
- [ ] **Step 3a: Change New Session action in core-items.ts**
In `src/core/menu/core-items.ts`, replace line 9:
```typescript
action: { type: 'delegate', prompt: 'User wants new session. Guide them through agent and workspace selection.' },
```
With:
```typescript
action: { type: 'callback', callbackData: 'ns:start' },
```
### Step 4: Build and commit
- [ ] **Step 4a: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 4b: Commit**
```bash
git add src/plugins/telegram/commands/new-session.ts \
src/plugins/telegram/commands/index.ts \
src/core/menu/core-items.ts
git commit -m "feat: button-driven New Session flow
New Session menu button now shows:
1. Agent picker (inline buttons, skip if only 1 agent)
2. Workspace picker (recent workspaces from session history)
3. 'Custom path...' delegates to AI for text input
4. Direct workspace selection creates session immediately
Uses workspace cache with numeric IDs to stay within
Telegram's 64-byte callback data limit."
```
---
## Task 7: Add re-export for telegram-overrides
**Files:**
- Modify: `src/plugins/telegram/commands/index.ts`
- [ ] **Step 1: Add re-export**
Add to the re-exports section at the bottom of `index.ts`:
```typescript
export { TELEGRAM_OVERRIDES } from './telegram-overrides.js'
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/commands/index.ts
git commit -m "chore: re-export TELEGRAM_OVERRIDES from commands index"
```
---
## Task 8: Manual Smoke Test
No automated tests for UI callback flows — these require grammY bot context which is hard to mock meaningfully. Verify manually.
- [ ] **Step 1: Build and start**
```bash
cd /Users/lucas/openacp-workspace/OpenACP && pnpm build
```
- [ ] **Step 2: Test each menu button in Telegram**
Open the Telegram group, type `/menu`, then test each button:
| Button | Expected behavior | Pass? |
|--------|-------------------|-------|
| 🆕 New Session | Shows agent picker buttons (or workspace picker if 1 agent) | |
| 📋 Sessions | Shows session list with status emoji + cleanup buttons + Refresh | |
| 📊 Status | Shows status text | |
| 🤖 Agents | Shows paginated agent list with install buttons | |
| ⚙️ Settings | Shows settings keyboard with toggle/select options | |
| 🔗 Integrate | Shows integration menu | |
| 🔄 Restart | Sends restart message, then restarts | |
| ⬆️ Update | Checks version, updates if available | |
| ❓ Help | Shows rich formatted help | |
| 🩺 Doctor | Runs diagnostics, shows report with fix buttons | |
- [ ] **Step 3: Test slash commands**
Type each command directly:
| Command | Expected | Pass? |
|---------|----------|-------|
| `/agents` | Paginated list with install buttons | |
| `/sessions` | Session list with cleanup + refresh | |
| `/doctor` | Diagnostic report with fix buttons | |
| `/help` | Rich formatted help | |
- [ ] **Step 4: Test New Session full flow**
1. `/menu` → tap "🆕 New Session" → agent picker appears
2. Tap an agent → workspace picker appears (recent workspaces + Custom)
3. Tap a recent workspace → session created with topic
4. Repeat: tap "Custom path..." → AI asks for workspace path
- [ ] **Step 5: Test Refresh button**
1. `/menu` → tap "📋 Sessions" → session list with Refresh button
2. Tap "Refresh" → list refreshes

File diff suppressed because it is too large Load Diff

View File

@ -1,966 +0,0 @@
# Plugins API Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add `/api/v1/plugins` route group to the api-server plugin, exposing list, marketplace, enable, disable, and uninstall endpoints backed by `LifecycleManager` and `PluginRegistry`.
**Architecture:** A new `plugins.ts` route file is registered in `api-server/index.ts`. It receives `lifecycleManager` via `RouteDeps`. Two getters are added to `LifecycleManager` to expose its private `loadOrder` array and `instanceRoot`. All endpoints require `system:admin` scope.
**Tech Stack:** Fastify, Vitest, TypeScript ESM (`.js` imports), `LifecycleManager`, `PluginRegistry`, `RegistryClient`, `importFromDir`.
---
## File Map
| Action | File | Responsibility |
|--------|------|----------------|
| Modify | `src/core/plugin/lifecycle-manager.ts` | Add `plugins` and `instanceRoot` public getters |
| Modify | `src/plugins/api-server/routes/types.ts` | Add `lifecycleManager?: LifecycleManager` to `RouteDeps` |
| Create | `src/plugins/api-server/routes/plugins.ts` | All 5 plugin endpoints |
| Create | `src/plugins/api-server/__tests__/routes-plugins.test.ts` | Full route test suite |
| Modify | `src/plugins/api-server/index.ts` | Import, wire, and register plugins route |
---
### Task 1: Add public getters to LifecycleManager
`loadOrder` and `instanceRoot` are both private but needed by the route. Add getters without breaking the existing API.
**Files:**
- Modify: `src/core/plugin/lifecycle-manager.ts`
- [ ] **Step 1: Rename private field and add getters**
In `src/core/plugin/lifecycle-manager.ts`, rename `private instanceRoot` to `private _instanceRoot`, then add two getters after the existing `get registry()` getter:
```ts
// Change:
private instanceRoot: string | undefined
// To:
private _instanceRoot: string | undefined
```
Update all internal uses of `this.instanceRoot` to `this._instanceRoot` (constructor assignment and createPluginContext call):
```ts
// constructor:
this._instanceRoot = opts?.instanceRoot
// createPluginContext call:
instanceRoot: this._instanceRoot,
```
Add getters after `get registry()`:
```ts
/** Plugin definitions currently in load order (loaded + failed). */
get plugins(): OpenACPPlugin[] {
return [...this.loadOrder]
}
/** Root directory of this OpenACP instance (e.g. ~/.openacp). */
get instanceRoot(): string | undefined {
return this._instanceRoot
}
```
- [ ] **Step 2: Run existing lifecycle tests to verify no regression**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/core/plugin/__tests__/lifecycle-manager.test.ts
```
Expected: all tests pass.
- [ ] **Step 3: Commit**
```bash
git add src/core/plugin/lifecycle-manager.ts
git commit -m "feat(lifecycle): expose plugins and instanceRoot as public getters"
```
---
### Task 2: Extend RouteDeps
**Files:**
- Modify: `src/plugins/api-server/routes/types.ts`
- [ ] **Step 1: Add import and field**
In `src/plugins/api-server/routes/types.ts`, add:
```ts
import type { LifecycleManager } from '../../../core/plugin/lifecycle-manager.js'
export interface RouteDeps {
core: OpenACPCore;
topicManager?: TopicManager;
startedAt: number;
getVersion: () => string;
commandRegistry?: CommandRegistry;
authPreHandler?: preHandlerHookHandler;
contextManager?: ContextManager;
/** LifecycleManager for plugin state queries and hot-load operations. */
lifecycleManager?: LifecycleManager;
}
```
- [ ] **Step 2: Verify TypeScript compiles**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | head -20
```
Expected: no errors related to `RouteDeps`.
- [ ] **Step 3: Commit**
```bash
git add src/plugins/api-server/routes/types.ts
git commit -m "feat(api-server): add lifecycleManager to RouteDeps"
```
---
### Task 3: Create plugins route — GET /plugins
**Files:**
- Create: `src/plugins/api-server/routes/plugins.ts`
- Create: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
- [ ] **Step 1: Write the failing test for GET /plugins**
Create `src/plugins/api-server/__tests__/routes-plugins.test.ts`:
```ts
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { createApiServer } from '../server.js'
import { TokenStore } from '../auth/token-store.js'
import { pluginRoutes } from '../routes/plugins.js'
import type { RouteDeps } from '../routes/types.js'
import type { LifecycleManager } from '../../../core/plugin/lifecycle-manager.js'
import type { PluginRegistry, PluginEntry } from '../../../core/plugin/plugin-registry.js'
import type { OpenACPPlugin } from '../../../core/plugin/types.js'
import * as fs from 'node:fs'
import * as path from 'node:path'
import * as os from 'node:os'
const SECRET = 'b'.repeat(64)
const JWT_SECRET = 'plugin-test-jwt-secret'
function authHeaders() {
return { authorization: `Bearer ${SECRET}` }
}
function makeRegistry(entries: Record<string, Partial<PluginEntry>>): PluginRegistry {
return {
list: () => new Map(Object.entries(entries).map(([name, e]) => [name, {
version: '1.0.0',
installedAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
source: 'builtin' as const,
enabled: true,
settingsPath: '/tmp/settings.json',
...e,
}])),
get: (name: string) => {
const e = entries[name]
if (!e) return undefined
return {
version: '1.0.0',
installedAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
source: 'builtin' as const,
enabled: true,
settingsPath: '/tmp/settings.json',
...e,
}
},
setEnabled: () => {},
remove: () => {},
save: async () => {},
register: () => {},
} as unknown as PluginRegistry
}
function makeLifecycleManager(opts: {
registryEntries?: Record<string, Partial<PluginEntry>>
loadedPlugins?: string[]
failedPlugins?: string[]
pluginDefs?: OpenACPPlugin[]
instanceRoot?: string
bootFn?: (plugins: OpenACPPlugin[]) => Promise<void>
unloadFn?: (name: string) => Promise<void>
}): LifecycleManager {
return {
registry: makeRegistry(opts.registryEntries ?? {}),
loadedPlugins: opts.loadedPlugins ?? [],
failedPlugins: opts.failedPlugins ?? [],
plugins: opts.pluginDefs ?? [],
instanceRoot: opts.instanceRoot,
boot: opts.bootFn ?? (async () => {}),
unloadPlugin: opts.unloadFn ?? (async () => {}),
} as unknown as LifecycleManager
}
describe('plugin routes', () => {
let server: Awaited<ReturnType<typeof createApiServer>> | null = null
let tokenStore: TokenStore
let tmpDir: string
async function buildServer(lm: LifecycleManager) {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-routes-test-'))
const tokensFile = path.join(tmpDir, 'tokens.json')
tokenStore = new TokenStore(tokensFile)
await tokenStore.load()
server = await createApiServer({
port: 0,
host: '127.0.0.1',
getSecret: () => SECRET,
getJwtSecret: () => JWT_SECRET,
tokenStore,
})
const deps: Partial<RouteDeps> = {
lifecycleManager: lm,
}
server.registerPlugin('/api/v1/plugins', async (app) => {
await pluginRoutes(app, deps as RouteDeps)
})
await server.app.ready()
}
afterEach(async () => {
if (server) {
await server.app.close()
server = null
}
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true })
})
describe('GET /api/v1/plugins', () => {
it('returns installed plugins with runtime state', async () => {
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/telegram': { source: 'builtin', enabled: true },
'@openacp/translator': { source: 'npm', enabled: false },
},
loadedPlugins: ['@openacp/telegram'],
failedPlugins: [],
pluginDefs: [
{ name: '@openacp/telegram', version: '1.0.0', essential: true, configure: async () => {}, setup: async () => {} } as unknown as OpenACPPlugin,
],
})
await buildServer(lm)
const res = await server!.app.inject({
method: 'GET',
url: '/api/v1/plugins',
headers: authHeaders(),
})
expect(res.statusCode).toBe(200)
const body = JSON.parse(res.body)
expect(body.plugins).toHaveLength(2)
const telegram = body.plugins.find((p: any) => p.name === '@openacp/telegram')
expect(telegram).toMatchObject({
name: '@openacp/telegram',
source: 'builtin',
enabled: true,
loaded: true,
failed: false,
essential: true,
hasConfigure: true,
})
const translator = body.plugins.find((p: any) => p.name === '@openacp/translator')
expect(translator).toMatchObject({
name: '@openacp/translator',
source: 'npm',
enabled: false,
loaded: false,
failed: false,
essential: false,
hasConfigure: false,
})
})
it('returns 401 without auth', async () => {
await buildServer(makeLifecycleManager({}))
const res = await server!.app.inject({ method: 'GET', url: '/api/v1/plugins' })
expect(res.statusCode).toBe(401)
})
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts 2>&1 | head -20
```
Expected: FAIL — `Cannot find module '../routes/plugins.js'`
- [ ] **Step 3: Create plugins route with GET /plugins**
Create `src/plugins/api-server/routes/plugins.ts`:
```ts
import type { FastifyInstance } from 'fastify'
import type { RouteDeps } from './types.js'
import { requireScopes } from '../middleware/auth.js'
import { corePlugins } from '../../../plugins/core-plugins.js'
export async function pluginRoutes(
app: FastifyInstance,
deps: RouteDeps,
): Promise<void> {
const { lifecycleManager } = deps
const admin = [requireScopes('system:admin')]
// GET /plugins — list all installed plugins with runtime state
app.get('/', { preHandler: admin }, async () => {
if (!lifecycleManager?.registry) return { plugins: [] }
const registry = lifecycleManager.registry
const loadedSet = new Set(lifecycleManager.loadedPlugins)
const failedSet = new Set(lifecycleManager.failedPlugins)
const loadOrderMap = new Map(lifecycleManager.plugins.map((p) => [p.name, p]))
const coreMap = new Map(corePlugins.map((p) => [p.name, p]))
const plugins = Array.from(registry.list().entries()).map(([name, entry]) => {
const def = loadOrderMap.get(name) ?? coreMap.get(name)
return {
name,
version: entry.version,
description: entry.description,
source: entry.source,
enabled: entry.enabled,
loaded: loadedSet.has(name),
failed: failedSet.has(name),
essential: def?.essential ?? false,
hasConfigure: typeof def?.configure === 'function',
}
})
return { plugins }
})
}
```
- [ ] **Step 4: Run test to verify GET /plugins passes**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗|PASS|FAIL|GET /api"
```
Expected: both GET /plugins tests pass.
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
git commit -m "feat(api-server): add GET /plugins endpoint"
```
---
### Task 4: GET /plugins/marketplace
**Files:**
- Modify: `src/plugins/api-server/routes/plugins.ts`
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
- [ ] **Step 1: Write failing tests for marketplace**
Add to the `describe('plugin routes')` block in the test file:
```ts
describe('GET /api/v1/plugins/marketplace', () => {
it('returns marketplace plugins with installed flag', async () => {
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/telegram': { source: 'builtin', enabled: true },
},
})
await buildServer(lm)
// Mock the RegistryClient by intercepting the dynamic import
// We can test via the actual fetch, but for unit test we rely on
// the 503 path when the registry is unreachable.
const res = await server!.app.inject({
method: 'GET',
url: '/api/v1/plugins/marketplace',
headers: authHeaders(),
})
// Registry fetch will fail in test env (no internet) — expect 503
expect(res.statusCode).toBe(503)
const body = JSON.parse(res.body)
expect(body.error).toBe('Marketplace unavailable')
})
it('returns 401 without auth', async () => {
await buildServer(makeLifecycleManager({}))
const res = await server!.app.inject({ method: 'GET', url: '/api/v1/plugins/marketplace' })
expect(res.statusCode).toBe(401)
})
})
```
- [ ] **Step 2: Run to verify new tests fail**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗|marketplace"
```
Expected: FAIL — marketplace route not yet registered.
- [ ] **Step 3: Add GET /plugins/marketplace to plugins.ts**
Append to `pluginRoutes` function in `src/plugins/api-server/routes/plugins.ts`:
```ts
// GET /plugins/marketplace — proxy to RegistryClient with installed flag
app.get('/marketplace', { preHandler: admin }, async (_req, reply) => {
try {
const { RegistryClient } = await import('../../../core/plugin/registry-client.js')
const client = new RegistryClient()
const data = await client.getRegistry()
const installedNames = new Set(
lifecycleManager?.registry
? Array.from(lifecycleManager.registry.list().keys())
: [],
)
const plugins = data.plugins.map((p) => ({
...p,
installed: installedNames.has(p.name) || installedNames.has(p.npm),
}))
return { plugins, categories: data.categories }
} catch {
return reply.status(503).send({ error: 'Marketplace unavailable' })
}
})
```
- [ ] **Step 4: Run tests**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
```
Expected: all 4 tests pass (GET /plugins ×2, marketplace ×2).
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
git commit -m "feat(api-server): add GET /plugins/marketplace endpoint"
```
---
### Task 5: POST /plugins/:name/enable
**Files:**
- Modify: `src/plugins/api-server/routes/plugins.ts`
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
- [ ] **Step 1: Write failing tests**
Add to the test file:
```ts
describe('POST /api/v1/plugins/:name/enable', () => {
it('enables and boots a disabled builtin plugin', async () => {
let booted: string[] = []
let registryEnabled: Record<string, boolean> = {}
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/context': { source: 'builtin', enabled: false },
},
loadedPlugins: [],
pluginDefs: [],
bootFn: async (plugins) => { booted = plugins.map(p => p.name) },
})
;(lm.registry as any).setEnabled = (name: string, val: boolean) => { registryEnabled[name] = val }
await buildServer(lm)
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Fcontext/enable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(200)
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
})
it('is idempotent when plugin is already loaded', async () => {
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/context': { source: 'builtin', enabled: true },
},
loadedPlugins: ['@openacp/context'],
})
await buildServer(lm)
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Fcontext/enable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(200)
})
it('returns 404 for unknown plugin', async () => {
await buildServer(makeLifecycleManager({}))
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Funknown/enable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(404)
})
})
```
- [ ] **Step 2: Run to verify tests fail**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "enable|✓|✗"
```
Expected: FAIL — route not yet implemented.
- [ ] **Step 3: Add POST /:name/enable to plugins.ts**
Append to `pluginRoutes`:
```ts
// POST /plugins/:name/enable — hot-load a disabled plugin
app.post('/:name/enable', { preHandler: admin }, async (req, reply) => {
if (!lifecycleManager?.registry) {
return reply.status(503).send({ error: 'Plugin manager unavailable' })
}
const name = decodeURIComponent((req.params as { name: string }).name)
const registry = lifecycleManager.registry
const entry = registry.get(name)
if (!entry) {
return reply.status(404).send({ error: `Plugin "${name}" not found` })
}
// Idempotent — already loaded
if (lifecycleManager.loadedPlugins.includes(name)) {
registry.setEnabled(name, true)
await registry.save()
return { ok: true }
}
// Resolve plugin definition
let pluginDef = lifecycleManager.plugins.find((p) => p.name === name)
if (!pluginDef) {
if (entry.source === 'builtin') {
pluginDef = corePlugins.find((p) => p.name === name)
} else {
// npm / local — dynamic import
const { importFromDir } = await import('../../../core/plugin/plugin-installer.js')
const instanceRoot =
lifecycleManager.instanceRoot ??
(await import('node:path')).default.join(
(await import('node:os')).default.homedir(),
'.openacp',
)
const pluginsDir = (await import('node:path')).default.join(instanceRoot, 'plugins')
try {
const mod = await importFromDir(name, pluginsDir)
pluginDef = mod.default ?? mod
} catch {
return reply
.status(500)
.send({ error: 'Plugin module could not be loaded. Try restarting the server.' })
}
}
}
if (!pluginDef) {
return reply.status(500).send({ error: `Plugin definition not found for "${name}"` })
}
registry.setEnabled(name, true)
await registry.save()
await lifecycleManager.boot([pluginDef])
if (lifecycleManager.failedPlugins.includes(name)) {
return reply.status(500).send({ error: `Plugin "${name}" failed to start` })
}
return { ok: true }
})
```
- [ ] **Step 4: Run tests**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
```
Expected: all enable tests pass.
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
git commit -m "feat(api-server): add POST /plugins/:name/enable endpoint"
```
---
### Task 6: POST /plugins/:name/disable
**Files:**
- Modify: `src/plugins/api-server/routes/plugins.ts`
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
- [ ] **Step 1: Write failing tests**
Add to the test file:
```ts
describe('POST /api/v1/plugins/:name/disable', () => {
it('unloads and disables a loaded plugin', async () => {
let unloaded: string[] = []
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/context': { source: 'builtin', enabled: true },
},
loadedPlugins: ['@openacp/context'],
pluginDefs: [
{ name: '@openacp/context', version: '1.0.0', essential: false, setup: async () => {} } as unknown as OpenACPPlugin,
],
unloadFn: async (name) => { unloaded.push(name) },
})
await buildServer(lm)
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Fcontext/disable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(200)
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
expect(unloaded).toContain('@openacp/context')
})
it('returns 409 for essential plugin', async () => {
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/telegram': { source: 'builtin', enabled: true },
},
loadedPlugins: ['@openacp/telegram'],
pluginDefs: [
{ name: '@openacp/telegram', version: '1.0.0', essential: true, setup: async () => {} } as unknown as OpenACPPlugin,
],
})
await buildServer(lm)
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Ftelegram/disable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(409)
expect(JSON.parse(res.body).error).toContain('Essential')
})
it('returns 404 for unknown plugin', async () => {
await buildServer(makeLifecycleManager({}))
const res = await server!.app.inject({
method: 'POST',
url: '/api/v1/plugins/@openacp%2Funknown/disable',
headers: authHeaders(),
})
expect(res.statusCode).toBe(404)
})
})
```
- [ ] **Step 2: Run to verify tests fail**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "disable|✓|✗"
```
Expected: FAIL — route not yet implemented.
- [ ] **Step 3: Add POST /:name/disable to plugins.ts**
Append to `pluginRoutes`:
```ts
// POST /plugins/:name/disable — unload and disable a plugin
app.post('/:name/disable', { preHandler: admin }, async (req, reply) => {
if (!lifecycleManager?.registry) {
return reply.status(503).send({ error: 'Plugin manager unavailable' })
}
const name = decodeURIComponent((req.params as { name: string }).name)
const registry = lifecycleManager.registry
const entry = registry.get(name)
if (!entry) {
return reply.status(404).send({ error: `Plugin "${name}" not found` })
}
// Check essential — look in loadOrder first, fall back to corePlugins
const def =
lifecycleManager.plugins.find((p) => p.name === name) ??
corePlugins.find((p) => p.name === name)
if (def?.essential) {
return reply.status(409).send({ error: 'Essential plugins cannot be disabled' })
}
await lifecycleManager.unloadPlugin(name)
registry.setEnabled(name, false)
await registry.save()
return { ok: true }
})
```
- [ ] **Step 4: Run tests**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
```
Expected: all disable tests pass.
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
git commit -m "feat(api-server): add POST /plugins/:name/disable endpoint"
```
---
### Task 7: DELETE /plugins/:name (uninstall)
**Files:**
- Modify: `src/plugins/api-server/routes/plugins.ts`
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
- [ ] **Step 1: Write failing tests**
Add to the test file:
```ts
describe('DELETE /api/v1/plugins/:name', () => {
it('unloads and removes an npm plugin', async () => {
let unloaded: string[] = []
let removed: string[] = []
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/translator': { source: 'npm', enabled: true },
},
loadedPlugins: ['@openacp/translator'],
unloadFn: async (name) => { unloaded.push(name) },
})
;(lm.registry as any).remove = (name: string) => { removed.push(name) }
await buildServer(lm)
const res = await server!.app.inject({
method: 'DELETE',
url: '/api/v1/plugins/@openacp%2Ftranslator',
headers: authHeaders(),
})
expect(res.statusCode).toBe(200)
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
expect(unloaded).toContain('@openacp/translator')
expect(removed).toContain('@openacp/translator')
})
it('returns 400 for builtin plugin', async () => {
const lm = makeLifecycleManager({
registryEntries: {
'@openacp/telegram': { source: 'builtin', enabled: true },
},
})
await buildServer(lm)
const res = await server!.app.inject({
method: 'DELETE',
url: '/api/v1/plugins/@openacp%2Ftelegram',
headers: authHeaders(),
})
expect(res.statusCode).toBe(400)
expect(JSON.parse(res.body).error).toContain('Builtin')
})
it('returns 404 for unknown plugin', async () => {
await buildServer(makeLifecycleManager({}))
const res = await server!.app.inject({
method: 'DELETE',
url: '/api/v1/plugins/@openacp%2Funknown',
headers: authHeaders(),
})
expect(res.statusCode).toBe(404)
})
})
```
- [ ] **Step 2: Run to verify tests fail**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "DELETE|uninstall|✓|✗"
```
Expected: FAIL — route not yet implemented.
- [ ] **Step 3: Add DELETE /:name to plugins.ts**
Append to `pluginRoutes`:
```ts
// DELETE /plugins/:name — uninstall (remove from registry, unload)
app.delete('/:name', { preHandler: admin }, async (req, reply) => {
if (!lifecycleManager?.registry) {
return reply.status(503).send({ error: 'Plugin manager unavailable' })
}
const name = decodeURIComponent((req.params as { name: string }).name)
const registry = lifecycleManager.registry
const entry = registry.get(name)
if (!entry) {
return reply.status(404).send({ error: `Plugin "${name}" not found` })
}
if (entry.source === 'builtin') {
return reply
.status(400)
.send({ error: 'Builtin plugins cannot be uninstalled. Use disable instead.' })
}
await lifecycleManager.unloadPlugin(name)
registry.remove(name)
await registry.save()
return { ok: true }
})
```
- [ ] **Step 4: Run all plugin route tests**
```bash
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose
```
Expected: all tests pass.
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
git commit -m "feat(api-server): add DELETE /plugins/:name endpoint"
```
---
### Task 8: Register plugins route in api-server/index.ts
**Files:**
- Modify: `src/plugins/api-server/index.ts`
- [ ] **Step 1: Wire lifecycleManager into RouteDeps and register the route**
In `src/plugins/api-server/index.ts`, find the `setup(ctx)` function. After the existing imports and before `const deps: RouteDeps = {`:
Add import at top of the setup function (alongside the other route imports):
```ts
const { pluginRoutes } = await import('./routes/plugins.js')
```
Add `lifecycleManager` to the deps object:
```ts
const deps: RouteDeps = {
core,
topicManager,
startedAt,
getVersion,
commandRegistry,
authPreHandler: routeAuthPreHandler,
contextManager,
lifecycleManager: core.lifecycleManager, // ← add this line
}
```
Register the route after the existing `server.registerPlugin` calls:
```ts
server.registerPlugin('/api/v1/plugins', async (app) => pluginRoutes(app, deps))
```
- [ ] **Step 2: Run full test suite to check for regressions**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test 2>&1 | tail -20
```
Expected: all tests pass, no regressions.
- [ ] **Step 3: Build to verify TypeScript**
```bash
pnpm build 2>&1 | grep -E "error|Error" | head -10
```
Expected: no errors.
- [ ] **Step 4: Commit**
```bash
git add src/plugins/api-server/index.ts
git commit -m "feat(api-server): register /api/v1/plugins route group"
```

File diff suppressed because it is too large Load Diff

View File

@ -1,504 +0,0 @@
# Session List History Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** `GET /sessions` returns all sessions (live + historical) so the App can show full session history including cancelled and finished sessions.
**Architecture:** Add `SessionSummary` interface and `listAllSessions()` method to `SessionManager` that merges store records (all statuses) with live in-memory session data. Route switches from `listSessions()` to `listAllSessions()`. Historical sessions get `queueDepth: 0`, `promptRunning: false`, `isLive: false`.
**Tech Stack:** TypeScript, Vitest, Fastify
---
## File Map
| File | Change |
|------|--------|
| `src/core/sessions/session-manager.ts` | Add `SessionSummary` interface + `listAllSessions()` method |
| `src/core/sessions/__tests__/session-manager.test.ts` | Add tests for `listAllSessions()` |
| `src/plugins/api-server/routes/sessions.ts` | Update `GET /` to use `listAllSessions()`, add `isLive`/`channelId`/`lastActiveAt` to response |
| `src/plugins/api-server/__tests__/routes-sessions.test.ts` | Add `listAllSessions` to mock, update/add tests |
---
### Task 1: Add `SessionSummary` + `listAllSessions()` to SessionManager (TDD)
**Files:**
- Modify: `src/core/sessions/session-manager.ts`
- Test: `src/core/sessions/__tests__/session-manager.test.ts`
- [ ] **Step 1: Write failing tests for `listAllSessions()`**
Append to `src/core/sessions/__tests__/session-manager.test.ts`:
```typescript
describe('listAllSessions', () => {
it('returns live session with isLive=true and runtime fields', () => {
const manager = new SessionManager(null)
const session = createSession({ id: 'sess-1', channelId: 'telegram' })
session.activate()
manager.registerSession(session)
const summaries = manager.listAllSessions()
expect(summaries).toHaveLength(1)
expect(summaries[0]).toMatchObject({
id: 'sess-1',
agent: 'claude',
status: 'active',
channelId: 'telegram',
workspace: '/workspace',
isLive: true,
promptRunning: false,
queueDepth: 0,
})
})
it('returns historical session (store only) with isLive=false and zero runtime fields', async () => {
const store = mockStore()
const manager = new SessionManager(store)
await store.save({
sessionId: 'old-sess',
agentSessionId: 'agent-old',
agentName: 'gemini',
workingDir: '/old',
channelId: 'telegram',
status: 'cancelled',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-02T00:00:00Z',
name: 'Old Session',
platform: {},
})
const summaries = manager.listAllSessions()
expect(summaries).toHaveLength(1)
expect(summaries[0]).toMatchObject({
id: 'old-sess',
agent: 'gemini',
status: 'cancelled',
name: 'Old Session',
workspace: '/old',
lastActiveAt: '2026-01-02T00:00:00Z',
dangerousMode: false,
queueDepth: 0,
promptRunning: false,
capabilities: null,
isLive: false,
})
expect(summaries[0].configOptions).toBeUndefined()
})
it('overlays live data onto store record when session is in memory', async () => {
const store = mockStore()
const manager = new SessionManager(store)
const session = createSession({ id: 'live-sess', channelId: 'telegram' })
session.activate()
manager.registerSession(session)
await store.save({
sessionId: 'live-sess',
agentSessionId: 'agent-live',
agentName: 'claude',
workingDir: '/workspace',
channelId: 'telegram',
status: 'active',
createdAt: session.createdAt.toISOString(),
lastActiveAt: '2026-04-03T10:00:00Z',
platform: {},
})
const summaries = manager.listAllSessions()
expect(summaries).toHaveLength(1)
expect(summaries[0].isLive).toBe(true)
expect(summaries[0].id).toBe('live-sess')
// lastActiveAt comes from store record
expect(summaries[0].lastActiveAt).toBe('2026-04-03T10:00:00Z')
})
it('returns both live and historical when mixed', async () => {
const store = mockStore()
const manager = new SessionManager(store)
// Live session registered in memory AND store
const live = createSession({ id: 'live-sess', channelId: 'telegram' })
live.activate()
manager.registerSession(live)
await store.save({
sessionId: 'live-sess',
agentSessionId: 'agent-live',
agentName: 'claude',
workingDir: '/workspace',
channelId: 'telegram',
status: 'active',
createdAt: live.createdAt.toISOString(),
lastActiveAt: '2026-04-03T10:00:00Z',
platform: {},
})
// Historical session only in store
await store.save({
sessionId: 'old-sess',
agentSessionId: 'agent-old',
agentName: 'gemini',
workingDir: '/old',
channelId: 'telegram',
status: 'cancelled',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-02T00:00:00Z',
platform: {},
})
const summaries = manager.listAllSessions()
expect(summaries).toHaveLength(2)
const liveResult = summaries.find(s => s.id === 'live-sess')!
const histResult = summaries.find(s => s.id === 'old-sess')!
expect(liveResult.isLive).toBe(true)
expect(histResult.isLive).toBe(false)
// No duplicates
expect(summaries.filter(s => s.id === 'live-sess')).toHaveLength(1)
})
it('falls back to live-only when no store', () => {
const manager = new SessionManager(null)
const session = createSession({ id: 'sess-1', channelId: 'telegram' })
session.activate()
manager.registerSession(session)
const summaries = manager.listAllSessions()
expect(summaries).toHaveLength(1)
expect(summaries[0].isLive).toBe(true)
expect(summaries[0].id).toBe('sess-1')
})
it('filters by channelId', async () => {
const store = mockStore()
const manager = new SessionManager(store)
await store.save({
sessionId: 'tg-sess',
agentSessionId: 'a1',
agentName: 'claude',
workingDir: '/w',
channelId: 'telegram',
status: 'cancelled',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-01T00:00:00Z',
platform: {},
})
await store.save({
sessionId: 'api-sess',
agentSessionId: 'a2',
agentName: 'claude',
workingDir: '/w',
channelId: 'api',
status: 'finished',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-01T00:00:00Z',
platform: {},
})
const summaries = manager.listAllSessions('telegram')
expect(summaries).toHaveLength(1)
expect(summaries[0].id).toBe('tg-sess')
})
it('historical session with acpState returns configOptions and capabilities', async () => {
const store = mockStore()
const manager = new SessionManager(store)
const configOptions = [{ id: 'mode', name: 'Mode', category: 'mode', type: 'select' as const, currentValue: 'auto', options: [] }]
await store.save({
sessionId: 'sess-acp',
agentSessionId: 'agent-acp',
agentName: 'claude',
workingDir: '/w',
channelId: 'api',
status: 'finished',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-01T00:00:00Z',
platform: {},
acpState: { configOptions },
})
const summaries = manager.listAllSessions()
expect(summaries[0].configOptions).toEqual(configOptions)
})
})
```
- [ ] **Step 2: Run tests to confirm they fail**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/core/sessions/__tests__/session-manager.test.ts 2>&1 | tail -20
```
Expected: FAIL — `manager.listAllSessions is not a function`
- [ ] **Step 3: Add `SessionSummary` interface and `listAllSessions()` to `session-manager.ts`**
Add import at the top of `src/core/sessions/session-manager.ts` (after existing imports):
```typescript
import type { SessionStatus, ConfigOption, AgentCapabilities } from "../types.js";
```
Add `SessionSummary` interface after the imports, before the class:
```typescript
export interface SessionSummary {
id: string;
agent: string;
status: SessionStatus;
name: string | null;
workspace: string;
channelId: string;
createdAt: string;
lastActiveAt: string | null;
dangerousMode: boolean;
queueDepth: number;
promptRunning: boolean;
configOptions?: ConfigOption[];
capabilities: AgentCapabilities | null;
isLive: boolean;
}
```
Add `listAllSessions()` method to the `SessionManager` class, after `listSessions()`:
```typescript
listAllSessions(channelId?: string): SessionSummary[] {
if (this.store) {
let records = this.store.list();
if (channelId) records = records.filter((r) => r.channelId === channelId);
return records.map((record) => {
const live = this.sessions.get(record.sessionId);
if (live) {
return {
id: live.id,
agent: live.agentName,
status: live.status,
name: live.name ?? null,
workspace: live.workingDirectory,
channelId: live.channelId,
createdAt: live.createdAt.toISOString(),
lastActiveAt: record.lastActiveAt ?? null,
dangerousMode: live.clientOverrides.bypassPermissions ?? false,
queueDepth: live.queueDepth,
promptRunning: live.promptRunning,
configOptions: live.configOptions?.length ? live.configOptions : undefined,
capabilities: live.agentCapabilities ?? null,
isLive: true,
};
}
return {
id: record.sessionId,
agent: record.agentName,
status: record.status,
name: record.name ?? null,
workspace: record.workingDir,
channelId: record.channelId,
createdAt: record.createdAt,
lastActiveAt: record.lastActiveAt ?? null,
dangerousMode: record.clientOverrides?.bypassPermissions ?? false,
queueDepth: 0,
promptRunning: false,
configOptions: record.acpState?.configOptions,
capabilities: record.acpState?.agentCapabilities ?? null,
isLive: false,
};
});
}
// Fallback: no store — return live sessions only
let live = Array.from(this.sessions.values());
if (channelId) live = live.filter((s) => s.channelId === channelId);
return live.map((s) => ({
id: s.id,
agent: s.agentName,
status: s.status,
name: s.name ?? null,
workspace: s.workingDirectory,
channelId: s.channelId,
createdAt: s.createdAt.toISOString(),
lastActiveAt: null,
dangerousMode: s.clientOverrides.bypassPermissions ?? false,
queueDepth: s.queueDepth,
promptRunning: s.promptRunning,
configOptions: s.configOptions?.length ? s.configOptions : undefined,
capabilities: s.agentCapabilities ?? null,
isLive: true,
}));
}
```
- [ ] **Step 4: Run tests to confirm they pass**
```bash
pnpm test src/core/sessions/__tests__/session-manager.test.ts 2>&1 | tail -20
```
Expected: All `listAllSessions` tests PASS.
- [ ] **Step 5: Commit**
```bash
git add src/core/sessions/session-manager.ts src/core/sessions/__tests__/session-manager.test.ts
git commit -m "feat: add SessionSummary + listAllSessions() to SessionManager"
```
---
### Task 2: Update `GET /sessions` route
**Files:**
- Modify: `src/plugins/api-server/routes/sessions.ts`
- Test: `src/plugins/api-server/__tests__/routes-sessions.test.ts`
- [ ] **Step 1: Write failing route test**
In `src/plugins/api-server/__tests__/routes-sessions.test.ts`, update `createMockDeps` to add `listAllSessions` to the mock:
```typescript
// In createMockDeps, add to sessionManager mock:
listAllSessions: vi.fn().mockReturnValue([
{
id: 'sess-1',
agent: 'claude',
status: 'active',
name: 'Test Session',
workspace: '/tmp/test',
channelId: 'api',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-01T00:00:00Z',
dangerousMode: false,
queueDepth: 0,
promptRunning: false,
configOptions: undefined,
capabilities: null,
isLive: true,
},
]),
```
Update the existing `GET /api/v1/sessions` test to verify new fields:
```typescript
describe('GET /api/v1/sessions', () => {
it('returns list of sessions with isLive and lastActiveAt', async () => {
const response = await app.inject({
method: 'GET',
url: '/api/v1/sessions',
});
expect(response.statusCode).toBe(200);
const body = JSON.parse(response.body);
expect(body.sessions).toHaveLength(1);
expect(body.sessions[0].id).toBe('sess-1');
expect(body.sessions[0].agent).toBe('claude');
expect(body.sessions[0].status).toBe('active');
expect(body.sessions[0].isLive).toBe(true);
expect(body.sessions[0].lastActiveAt).toBe('2026-01-01T00:00:00Z');
expect(body.sessions[0].channelId).toBe('api');
});
it('returns historical (non-live) sessions', async () => {
(deps.core.sessionManager.listAllSessions as any).mockReturnValue([
{
id: 'old-sess',
agent: 'claude',
status: 'cancelled',
name: 'Old Session',
workspace: '/tmp/old',
channelId: 'telegram',
createdAt: '2026-01-01T00:00:00Z',
lastActiveAt: '2026-01-02T00:00:00Z',
dangerousMode: false,
queueDepth: 0,
promptRunning: false,
configOptions: undefined,
capabilities: null,
isLive: false,
},
]);
const response = await app.inject({
method: 'GET',
url: '/api/v1/sessions',
});
expect(response.statusCode).toBe(200);
const body = JSON.parse(response.body);
expect(body.sessions[0].id).toBe('old-sess');
expect(body.sessions[0].status).toBe('cancelled');
expect(body.sessions[0].isLive).toBe(false);
});
});
```
- [ ] **Step 2: Run tests to confirm they fail**
```bash
pnpm test src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -20
```
Expected: FAIL — `listAllSessions is not a function` / missing fields in response.
- [ ] **Step 3: Update `GET /sessions` handler in `routes/sessions.ts`**
Replace the `GET /` handler (currently lines 24–44) with:
```typescript
// GET /sessions — list all sessions (live + historical)
app.get('/', { preHandler: requireScopes('sessions:read') }, async () => {
const summaries = deps.core.sessionManager.listAllSessions();
return {
sessions: summaries.map((s) => ({
id: s.id,
agent: s.agent,
status: s.status,
name: s.name,
workspace: s.workspace,
channelId: s.channelId,
createdAt: s.createdAt,
lastActiveAt: s.lastActiveAt,
dangerousMode: s.dangerousMode,
queueDepth: s.queueDepth,
promptRunning: s.promptRunning,
configOptions: s.configOptions,
capabilities: s.capabilities,
isLive: s.isLive,
})),
};
});
```
- [ ] **Step 4: Run tests to confirm they pass**
```bash
pnpm test src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -20
```
Expected: All tests PASS.
- [ ] **Step 5: Run full test suite to catch regressions**
```bash
pnpm test 2>&1 | tail -30
```
Expected: All tests pass. If any test fails due to missing `listAllSessions` in a mock, add it to that mock with `vi.fn().mockReturnValue([])`.
- [ ] **Step 6: Commit**
```bash
git add src/plugins/api-server/routes/sessions.ts src/plugins/api-server/__tests__/routes-sessions.test.ts
git commit -m "feat: GET /sessions returns full session history via listAllSessions"
```

View File

@ -1,508 +0,0 @@
# File Attachment API Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add optional `attachments` array to `POST /sessions/:id/prompt` (REST and SSE routes) so clients can upload base64-encoded files alongside a prompt.
**Architecture:** Schema validation (Zod) rejects bad mimeTypes and path traversal before any file I/O. A shared `decodeAttachments()` helper decodes base64 and saves via `FileService`, with cleanup on partial failure. REST and SSE routes both use the helper and preserve their existing `routing` argument to `enqueuePrompt`. Fastify `bodyLimit` is raised to 160 MB to allow the maximum payload.
**Tech Stack:** TypeScript, Fastify, Zod, Vitest, `FileService` (existing plugin)
---
## File Map
| Action | File | What changes |
|--------|------|--------------|
| Modify | `src/plugins/api-server/schemas/sessions.ts` | Add `AttachmentInputSchema`, extend `PromptBodySchema` |
| Create | `src/plugins/api-server/routes/attachments.ts` | Shared `decodeAttachments()` helper |
| Modify | `src/plugins/api-server/routes/sessions.ts` | Use `decodeAttachments`, fix `enqueuePrompt` call |
| Modify | `src/plugins/sse-adapter/routes.ts` | Same as above for SSE route |
| Modify | `src/plugins/api-server/server.ts` | Add `bodyLimit: 160 MB` |
| Modify | `.gitignore` | Add `**/.DS_Store` |
| Modify | `src/plugins/api-server/__tests__/routes-sessions.test.ts` | Add attachment test cases |
---
### Task 1: Schema — validation tests then implementation
**Files:**
- Modify: `src/plugins/api-server/__tests__/routes-sessions.test.ts`
- Modify: `src/plugins/api-server/schemas/sessions.ts`
- [ ] **Step 1: Add `fileService` mock to `createMockDeps`**
Open `src/plugins/api-server/__tests__/routes-sessions.test.ts`. In `createMockDeps()`, add `fileService` to the `core` mock object (at the same level as `sessionManager`):
```typescript
fileService: {
saveFile: vi.fn().mockResolvedValue({
type: 'image',
filePath: '/tmp/.openacp/files/sess-1/1234567890-photo.jpg',
fileName: 'photo.jpg',
mimeType: 'image/jpeg',
size: 100,
}),
},
```
The full `createMockDeps` core section should look like:
```typescript
core: {
sessionManager: { ... }, // existing
configManager: { ... }, // existing
agentCatalog: { ... }, // existing
adapters: new Map(), // existing
createSession: vi.fn()..., // existing
adoptSession: vi.fn()..., // existing
archiveSession: vi.fn()..., // existing
agentManager: { ... }, // existing
fileService: {
saveFile: vi.fn().mockResolvedValue({
type: 'image',
filePath: '/tmp/.openacp/files/sess-1/1234567890-photo.jpg',
fileName: 'photo.jpg',
mimeType: 'image/jpeg',
size: 100,
}),
},
} as any,
```
- [ ] **Step 2: Write failing schema validation tests**
Add a new `describe` block after the existing `POST /api/v1/sessions/:sessionId/prompt` block:
```typescript
describe('POST /api/v1/sessions/:sessionId/prompt — attachment validation', () => {
it('rejects more than 10 attachments with 400', async () => {
const attachments = Array.from({ length: 11 }, (_, i) => ({
fileName: `file${i}.jpg`,
mimeType: 'image/jpeg',
data: Buffer.from('x').toString('base64'),
}));
const response = await app.inject({
method: 'POST',
url: '/api/v1/sessions/sess-1/prompt',
payload: { prompt: 'hello', attachments },
});
expect(response.statusCode).toBe(400);
});
it('rejects path traversal in fileName with 400', async () => {
const response = await app.inject({
method: 'POST',
url: '/api/v1/sessions/sess-1/prompt',
payload: {
prompt: 'hello',
attachments: [{ fileName: '../../etc/passwd', mimeType: 'image/jpeg', data: 'aGk=' }],
},
});
expect(response.statusCode).toBe(400);
});
it('rejects unsupported mimeType with 400', async () => {
const response = await app.inject({
method: 'POST',
url: '/api/v1/sessions/sess-1/prompt',
payload: {
prompt: 'hello',
attachments: [{ fileName: 'script.html', mimeType: 'text/html', data: 'aGk=' }],
},
});
expect(response.statusCode).toBe(400);
});
});
```
- [ ] **Step 3: Run tests to confirm they fail**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test -- --reporter=verbose src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -30
```
Expected: 3 new tests FAIL (schema doesn't have `AttachmentInputSchema` yet, so attachments pass through and don't get validated — or Zod just ignores the unknown field).
- [ ] **Step 4: Implement `AttachmentInputSchema` and extend `PromptBodySchema`**
Open `src/plugins/api-server/schemas/sessions.ts`. Add before `PromptBodySchema`:
```typescript
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
'audio/ogg', 'audio/mpeg', 'audio/wav', 'audio/webm', 'audio/mp4',
'video/mp4', 'video/webm',
'application/pdf',
'text/plain',
]);
const AttachmentInputSchema = z.object({
fileName: z
.string()
.min(1)
.max(500)
.refine(
(v) => !v.includes('..') && !v.startsWith('/') && !v.startsWith('~'),
{ message: 'fileName must not contain path traversal sequences' },
),
mimeType: z
.string()
.refine((v) => ALLOWED_MIME_TYPES.has(v), { message: 'mimeType is not supported' }),
data: z.string().max(15_000_000), // ~10 MB base64 ≈ 13.3 MB string
});
export type AttachmentInput = z.infer<typeof AttachmentInputSchema>;
```
Then update `PromptBodySchema` to add the `attachments` field:
```typescript
export const PromptBodySchema = z.object({
// 100 KB limit — prevents memory exhaustion / DoS via enormous payloads
prompt: z.string().min(1).max(100_000),
// Multi-adapter routing fields
sourceAdapterId: z.string().optional(),
responseAdapterId: z.string().nullable().optional(),
// Optional file attachments — decoded from base64 and saved via FileService
attachments: z.array(AttachmentInputSchema).max(10).optional(),
});
```
- [ ] **Step 5: Run the schema validation tests — expect all 3 to pass**
```bash
pnpm test -- --reporter=verbose src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -30
```
Expected: 3 new tests PASS, all existing tests still PASS.
- [ ] **Step 6: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/api-server/schemas/sessions.ts src/plugins/api-server/__tests__/routes-sessions.test.ts
git commit -m "feat(api): add AttachmentInputSchema with mimeType allowlist and path traversal validation"
```
---
### Task 2: Shared `decodeAttachments` helper
**Files:**
- Create: `src/plugins/api-server/routes/attachments.ts`
- Modify: `src/plugins/api-server/__tests__/routes-sessions.test.ts`
- [ ] **Step 1: Write failing integration tests for attachment decode + enqueuePrompt**
Add to the `POST /api/v1/sessions/:sessionId/prompt` describe block in `routes-sessions.test.ts`:
```typescript
it('decodes attachment and passes it to enqueuePrompt with routing args', async () => {
const imageData = Buffer.from('fake-image-bytes').toString('base64');
const response = await app.inject({
method: 'POST',
url: '/api/v1/sessions/sess-1/prompt',
payload: {
prompt: 'describe this',
attachments: [{ fileName: 'photo.jpg', mimeType: 'image/jpeg', data: imageData }],
},
});
expect(response.statusCode).toBe(200);
const body = JSON.parse(response.body);
expect(body.ok).toBe(true);
// FileService.saveFile was called with decoded buffer
expect(deps.core.fileService.saveFile).toHaveBeenCalledWith(
'sess-1',
'photo.jpg',
Buffer.from('fake-image-bytes'),
'image/jpeg',
);
// enqueuePrompt received the saved Attachment and preserved routing
const session = (deps.core.sessionManager.getSession as any).mock.results[0].value;
expect(session.enqueuePrompt).toHaveBeenCalledWith(
'describe this',
[expect.objectContaining({ fileName: 'photo.jpg', mimeType: 'image/jpeg' })],
expect.objectContaining({ sourceAdapterId: 'api' }),
);
});
it('returns 500 and cleans up saved files when saveFile fails mid-batch', async () => {
// First call succeeds, second fails
(deps.core.fileService.saveFile as any)
.mockResolvedValueOnce({
type: 'image',
filePath: '/tmp/saved-first.jpg',
fileName: 'first.jpg',
mimeType: 'image/jpeg',
size: 50,
})
.mockRejectedValueOnce(new Error('disk full'));
const response = await app.inject({
method: 'POST',
url: '/api/v1/sessions/sess-1/prompt',
payload: {
prompt: 'two files',
attachments: [
{ fileName: 'first.jpg', mimeType: 'image/jpeg', data: 'aGk=' },
{ fileName: 'second.jpg', mimeType: 'image/jpeg', data: 'aGk=' },
],
},
});
expect(response.statusCode).toBe(500);
// enqueuePrompt must NOT have been called (no partial state)
const session = (deps.core.sessionManager.getSession as any).mock.results[0].value;
expect(session.enqueuePrompt).not.toHaveBeenCalled();
});
```
Also add `fs` mock at the top of the test file (needed for cleanup verification):
```typescript
import { vi } from 'vitest';
// already imported — no change needed
```
- [ ] **Step 2: Run tests to confirm they fail**
```bash
pnpm test -- --reporter=verbose src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -30
```
Expected: 2 new tests FAIL (route doesn't call `fileService.saveFile` yet).
- [ ] **Step 3: Create `src/plugins/api-server/routes/attachments.ts`**
```typescript
import fs from 'node:fs';
import type { Attachment } from '../../../core/types.js';
import type { FileServiceInterface } from '../../../core/plugin/types.js';
import type { AttachmentInput } from '../schemas/sessions.js';
/**
* Decode base64 attachments and save them via FileService.
* On partial failure, cleans up already-saved files before rethrowing.
*/
export async function decodeAttachments(
fileService: FileServiceInterface,
sessionId: string,
rawAttachments: AttachmentInput[],
): Promise<Attachment[]> {
const saved: Attachment[] = [];
try {
for (const att of rawAttachments) {
const buf = Buffer.from(att.data, 'base64');
const attachment = await fileService.saveFile(sessionId, att.fileName, buf, att.mimeType);
saved.push(attachment);
}
return saved;
} catch (err) {
// Clean up files saved before the failure
await Promise.allSettled(
saved.map((att) => fs.promises.rm(att.filePath, { force: true })),
);
throw err;
}
}
```
- [ ] **Step 4: Run tests — expect both new tests to pass**
```bash
pnpm test -- --reporter=verbose src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -30
```
Expected: still FAIL — routes haven't been updated yet to call `decodeAttachments`. That's fine; we'll fix in Task 3.
- [ ] **Step 5: Commit the helper file**
```bash
git add src/plugins/api-server/routes/attachments.ts
git commit -m "feat(api): add decodeAttachments helper with partial-failure cleanup"
```
---
### Task 3: Wire REST route + run all tests
**Files:**
- Modify: `src/plugins/api-server/routes/sessions.ts`
- [ ] **Step 1: Update imports in `sessions.ts`**
At the top of `src/plugins/api-server/routes/sessions.ts`, add the import:
```typescript
import { decodeAttachments } from './attachments.js';
```
The existing import block already imports `PromptBodySchema` from `../schemas/sessions.js` — no change needed there.
- [ ] **Step 2: Update the prompt route handler**
Find this block (around line 197–208):
```typescript
const body = PromptBodySchema.parse(request.body);
await session.enqueuePrompt(body.prompt, undefined, {
sourceAdapterId: body.sourceAdapterId ?? 'api',
responseAdapterId: body.responseAdapterId,
});
```
Replace it with:
```typescript
const body = PromptBodySchema.parse(request.body);
const attachments = body.attachments?.length
? await decodeAttachments(deps.core.fileService, sessionId, body.attachments)
: undefined;
await session.enqueuePrompt(body.prompt, attachments, {
sourceAdapterId: body.sourceAdapterId ?? 'api',
responseAdapterId: body.responseAdapterId,
});
```
- [ ] **Step 3: Run all route tests — expect all to pass**
```bash
pnpm test -- --reporter=verbose src/plugins/api-server/__tests__/routes-sessions.test.ts 2>&1 | tail -40
```
Expected: ALL tests pass including the 5 new ones from Tasks 1–2.
- [ ] **Step 4: Commit**
```bash
git add src/plugins/api-server/routes/sessions.ts
git commit -m "feat(api): wire attachment decoding in REST prompt route"
```
---
### Task 4: Wire SSE route
**Files:**
- Modify: `src/plugins/sse-adapter/routes.ts`
- [ ] **Step 1: Add import to `sse-adapter/routes.ts`**
At the top of `src/plugins/sse-adapter/routes.ts`, add:
```typescript
import { decodeAttachments } from '../api-server/routes/attachments.js';
```
- [ ] **Step 2: Update the SSE prompt route handler**
Find this block (around line 109–110):
```typescript
const body = PromptBodySchema.parse(request.body);
await session.enqueuePrompt(body.prompt, undefined, { sourceAdapterId: 'sse' });
```
Replace it with:
```typescript
const body = PromptBodySchema.parse(request.body);
const attachments = body.attachments?.length
? await decodeAttachments(deps.core.fileService, sessionId, body.attachments)
: undefined;
await session.enqueuePrompt(body.prompt, attachments, { sourceAdapterId: 'sse' });
```
- [ ] **Step 3: Build to verify TypeScript is happy**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds with no errors.
- [ ] **Step 4: Commit**
```bash
git add src/plugins/sse-adapter/routes.ts
git commit -m "feat(sse): wire attachment decoding in SSE prompt route"
```
---
### Task 5: Fastify body limit + .gitignore
**Files:**
- Modify: `src/plugins/api-server/server.ts`
- Modify: `.gitignore`
- [ ] **Step 1: Add `bodyLimit` to Fastify init**
In `src/plugins/api-server/server.ts`, find:
```typescript
const app = Fastify({ logger: options.logger ?? false, forceCloseConnections: true });
```
Replace with:
```typescript
const app = Fastify({
logger: options.logger ?? false,
forceCloseConnections: true,
// Support up to 10 attachments × ~15 MB base64 each
bodyLimit: 160 * 1024 * 1024,
});
```
- [ ] **Step 2: Add `.DS_Store` to `.gitignore`**
Open `.gitignore`, add at the top under the first comment:
```
**/.DS_Store
```
Full top section should read:
```gitignore
# References (external/third-party code)
references/
**/.DS_Store
node_modules/
dist/
```
- [ ] **Step 3: Run full test suite**
```bash
pnpm test 2>&1 | tail -20
```
Expected: all tests pass.
- [ ] **Step 4: Final build check**
```bash
pnpm build 2>&1 | tail -10
```
Expected: no errors.
- [ ] **Step 5: Commit**
```bash
git add src/plugins/api-server/server.ts .gitignore
git commit -m "chore: raise Fastify bodyLimit to 160 MB for attachment uploads, add .DS_Store to .gitignore"
```

File diff suppressed because it is too large Load Diff

View File

@ -1,896 +0,0 @@
# Persistent Assistant Session Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Reuse the same assistant session record across bot restarts instead of creating a new one each time, and hide assistant sessions from all session listings.
**Architecture:** Add `isAssistant` flag to `SessionRecord`, persist it on save, query it on startup to find existing assistant sessions, filter it out of all listing APIs. Replace `spawn()`/`respawn()` with `getOrSpawn()` that reuses the existing record ID.
**Tech Stack:** TypeScript, Vitest, existing SessionStore/SessionManager/AssistantManager patterns.
---
### Task 1: Add `isAssistant` to `SessionRecord` type
**Files:**
- Modify: `src/core/types.ts`
- [ ] **Step 1: Add field to `SessionRecord`**
In `src/core/types.ts`, add `isAssistant?: boolean` after `name?: string`:
```typescript
export interface SessionRecord<P = Record<string, unknown>> {
sessionId: string;
agentSessionId: string;
originalAgentSessionId?: string;
agentName: string;
workingDir: string;
channelId: string;
status: SessionStatus;
createdAt: string;
lastActiveAt: string;
name?: string;
isAssistant?: boolean; // ← add this line
dangerousMode?: boolean;
// ... rest unchanged
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build
```
Expected: Build succeeds (field is optional, no breakage).
- [ ] **Step 3: Commit**
```bash
git add src/core/types.ts
git commit -m "feat: add isAssistant field to SessionRecord type"
```
---
### Task 2: Add `findAssistant()` to `SessionStore` + exempt from TTL cleanup
**Files:**
- Modify: `src/core/sessions/session-store.ts`
- Test: `src/core/sessions/__tests__/session-store-comprehensive.test.ts`
- [ ] **Step 1: Write failing tests**
Open `src/core/sessions/__tests__/session-store-comprehensive.test.ts` and add this test block at the end (before the final closing `}`):
```typescript
describe('findAssistant', () => {
it('returns the assistant record for a channel', async () => {
const store = new JsonFileSessionStore(tmpFile(), 30);
await store.save({
sessionId: 'sess-1',
agentSessionId: 'agent-1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: true,
platform: {},
});
const result = store.findAssistant('telegram');
expect(result?.sessionId).toBe('sess-1');
store.destroy();
});
it('returns undefined when no assistant record for channel', async () => {
const store = new JsonFileSessionStore(tmpFile(), 30);
await store.save({
sessionId: 'sess-1',
agentSessionId: 'agent-1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: false,
platform: {},
});
expect(store.findAssistant('telegram')).toBeUndefined();
store.destroy();
});
it('ignores assistant records for other channels', async () => {
const store = new JsonFileSessionStore(tmpFile(), 30);
await store.save({
sessionId: 'sess-1',
agentSessionId: 'agent-1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'slack',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: true,
platform: {},
});
expect(store.findAssistant('telegram')).toBeUndefined();
store.destroy();
});
});
describe('TTL cleanup exempts assistant sessions', () => {
it('does not delete assistant records past TTL', async () => {
const store = new JsonFileSessionStore(tmpFile(), 1); // 1 day TTL
const oldDate = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(); // 3 days ago
await store.save({
sessionId: 'assistant-sess',
agentSessionId: 'agent-1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: oldDate,
lastActiveAt: oldDate,
isAssistant: true,
platform: {},
});
// Trigger cleanup by creating a new store that loads and cleans up
store.flush();
const store2 = new JsonFileSessionStore((store as any).filePath, 1);
expect(store2.get('assistant-sess')).toBeDefined();
store.destroy();
store2.destroy();
});
});
```
- [ ] **Step 2: Run tests to verify they fail**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/sessions/__tests__/session-store-comprehensive.test.ts 2>&1 | tail -20
```
Expected: Tests fail with `store.findAssistant is not a function`.
- [ ] **Step 3: Add `findAssistant` to `SessionStore` interface**
In `src/core/sessions/session-store.ts`, add to the `SessionStore` interface after `findByAgentSessionId`:
```typescript
export interface SessionStore {
save(record: SessionRecord): Promise<void>;
flush(): void;
get(sessionId: string): SessionRecord | undefined;
findByPlatform(
channelId: string,
predicate: (platform: Record<string, unknown>) => boolean,
): SessionRecord | undefined;
findByAgentSessionId(agentSessionId: string): SessionRecord | undefined;
findAssistant(channelId: string): SessionRecord | undefined; // ← add this
list(channelId?: string): SessionRecord[];
remove(sessionId: string): Promise<void>;
}
```
- [ ] **Step 4: Implement `findAssistant` in `JsonFileSessionStore`**
Add after the `findByAgentSessionId` method:
```typescript
findAssistant(channelId: string): SessionRecord | undefined {
for (const record of this.records.values()) {
if (record.isAssistant === true && record.channelId === channelId) {
return record;
}
}
return undefined;
}
```
- [ ] **Step 5: Exempt assistant sessions from TTL cleanup**
In `JsonFileSessionStore.cleanup()`, modify the skip condition:
```typescript
private cleanup(): void {
const cutoff = Date.now() - this.ttlDays * 24 * 60 * 60 * 1000;
let removed = 0;
for (const [id, record] of this.records) {
if (record.status === "active" || record.status === "initializing")
continue;
if (record.isAssistant === true) // ← add this line
continue;
const raw = record.lastActiveAt;
if (!raw) continue;
const lastActive = new Date(raw).getTime();
if (isNaN(lastActive)) continue;
if (lastActive < cutoff) {
this.records.delete(id);
removed++;
}
}
// ... rest unchanged
```
- [ ] **Step 6: Run tests to verify they pass**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/sessions/__tests__/session-store-comprehensive.test.ts 2>&1 | tail -20
```
Expected: All tests pass.
- [ ] **Step 7: Commit**
```bash
git add src/core/sessions/session-store.ts src/core/sessions/__tests__/session-store-comprehensive.test.ts
git commit -m "feat: add findAssistant() to SessionStore and exempt assistant records from TTL cleanup"
```
---
### Task 3: Persist `isAssistant` through `core.createSession()`
**Files:**
- Modify: `src/core/core.ts`
- Modify: `src/core/sessions/session-factory.ts`
The persistence path is: `AssistantManager.getOrSpawn()` → `core.createSession()` → `sessionFactory.create()` (creates session in memory) → `patchRecord()` (persists to store). Only `core.createSession()` and `SessionFactory.SessionCreateParams` need to be updated.
- [ ] **Step 1: Add `isAssistant` to `OpenACPCore.createSession()` signature and persistence**
In `src/core/core.ts`, update `createSession` signature:
```typescript
async createSession(params: {
channelId: string;
agentName: string;
workingDirectory: string;
resumeAgentSessionId?: string;
existingSessionId?: string;
createThread?: boolean;
initialName?: string;
threadId?: string;
isAssistant?: boolean; // ← add this
}): Promise<Session> {
```
Then in the `patchRecord` call (around line 463), add `isAssistant`:
```typescript
await this.sessionManager.patchRecord(session.id, {
sessionId: session.id,
agentSessionId: session.agentSessionId,
agentName: params.agentName,
workingDir: params.workingDirectory,
channelId: params.channelId,
status: session.status,
createdAt: session.createdAt.toISOString(),
lastActiveAt: new Date().toISOString(),
name: session.name,
isAssistant: params.isAssistant, // ← add this
platform,
platforms,
firstAgent: session.firstAgent,
currentPromptCount: session.promptCount,
agentSwitchHistory: session.agentSwitchHistory,
acpState: session.toAcpStateSnapshot(),
}, { immediate: true });
```
Also update `SessionFactory.SessionCreateParams` in `src/core/sessions/session-factory.ts` to add `isAssistant?: boolean` so the type is consistent with the `core.createSession()` params (they share the same type via `createFullSession`):
```typescript
export interface SessionCreateParams {
channelId: string;
agentName: string;
workingDirectory: string;
resumeAgentSessionId?: string;
existingSessionId?: string;
initialName?: string;
isAssistant?: boolean; // ← add this
}
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build 2>&1 | tail -30
```
Expected: Build succeeds.
- [ ] **Step 3: Commit**
```bash
git add src/core/core.ts src/core/sessions/session-factory.ts
git commit -m "feat: persist isAssistant flag through session creation pipeline"
```
---
### Task 4: Filter assistant sessions from all listings
**Files:**
- Modify: `src/core/sessions/session-manager.ts`
- Test: `src/core/sessions/__tests__/session-manager.test.ts`
- [ ] **Step 1: Write failing tests**
Open `src/core/sessions/__tests__/session-manager.test.ts` and add this describe block:
```typescript
describe('assistant session filtering', () => {
it('listSessions excludes assistant sessions', () => {
const manager = new SessionManager(null);
const regularSession = new Session({
channelId: 'telegram',
agentName: 'claude-code',
workingDirectory: '/tmp',
agentInstance: mockAgentInstance(),
});
const assistantSession = new Session({
channelId: 'telegram',
agentName: 'claude-code',
workingDirectory: '/tmp',
agentInstance: mockAgentInstance(),
isAssistant: true,
});
manager.registerSession(regularSession);
manager.registerSession(assistantSession);
const result = manager.listSessions();
expect(result).toContain(regularSession);
expect(result).not.toContain(assistantSession);
});
it('listAllSessions excludes assistant records', async () => {
const tmpPath = path.join(os.tmpdir(), `test-store-${Date.now()}.json`);
const store = new JsonFileSessionStore(tmpPath, 30);
const manager = new SessionManager(store);
await store.save({
sessionId: 'regular-1',
agentSessionId: 'a1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
platform: {},
});
await store.save({
sessionId: 'assistant-1',
agentSessionId: 'a2',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: true,
platform: {},
});
const summaries = manager.listAllSessions();
expect(summaries.some(s => s.id === 'regular-1')).toBe(true);
expect(summaries.some(s => s.id === 'assistant-1')).toBe(false);
store.destroy();
fs.unlinkSync(tmpPath);
});
it('listRecords excludes assistant records', async () => {
const tmpPath = path.join(os.tmpdir(), `test-store-${Date.now()}.json`);
const store = new JsonFileSessionStore(tmpPath, 30);
const manager = new SessionManager(store);
await store.save({
sessionId: 'regular-1',
agentSessionId: 'a1',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
platform: {},
});
await store.save({
sessionId: 'assistant-1',
agentSessionId: 'a2',
agentName: 'claude-code',
workingDir: '/tmp',
channelId: 'telegram',
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: true,
platform: {},
});
const records = manager.listRecords();
expect(records.some(r => r.sessionId === 'regular-1')).toBe(true);
expect(records.some(r => r.sessionId === 'assistant-1')).toBe(false);
store.destroy();
fs.unlinkSync(tmpPath);
});
});
```
Check existing imports at the top of the test file and add any missing ones (`path`, `os`, `fs`, `JsonFileSessionStore`).
- [ ] **Step 2: Run tests to verify they fail**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/sessions/__tests__/session-manager.test.ts 2>&1 | tail -20
```
Expected: New tests fail.
- [ ] **Step 3: Add filter to `listSessions()`**
In `src/core/sessions/session-manager.ts`, update `listSessions`:
```typescript
listSessions(channelId?: string): Session[] {
const all = Array.from(this.sessions.values()).filter(s => !s.isAssistant);
if (channelId) return all.filter((s) => s.channelId === channelId);
return all;
}
```
- [ ] **Step 4: Add filter to `listAllSessions()`**
In `src/core/sessions/session-manager.ts`, update the records variable in `listAllSessions`:
```typescript
listAllSessions(channelId?: string): SessionSummary[] {
if (this.store) {
let records = this.store.list().filter(r => !r.isAssistant); // ← add filter
if (channelId) records = records.filter((r) => r.channelId === channelId);
// ... rest unchanged
```
- [ ] **Step 5: Add filter to `listRecords()`**
In `src/core/sessions/session-manager.ts`, update `listRecords`:
```typescript
listRecords(filter?: {
statuses?: string[];
}): import("../types.js").SessionRecord[] {
if (!this.store) return [];
let records = this.store.list().filter(r => !r.isAssistant); // ← add filter
if (filter?.statuses?.length) {
records = records.filter((r) => filter.statuses!.includes(r.status));
}
return records;
}
```
- [ ] **Step 6: Run tests to verify they pass**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/sessions/__tests__/session-manager.test.ts 2>&1 | tail -20
```
Expected: All tests pass.
- [ ] **Step 7: Commit**
```bash
git add src/core/sessions/session-manager.ts src/core/sessions/__tests__/session-manager.test.ts
git commit -m "feat: filter assistant sessions from all session listings"
```
---
### Task 5: Replace `spawn()`/`respawn()` with `getOrSpawn()` in `AssistantManager`
**Files:**
- Modify: `src/core/assistant/assistant-manager.ts`
- Modify: `src/core/__tests__/assistant-manager.test.ts`
- [ ] **Step 1: Rewrite `assistant-manager.test.ts`**
Replace the entire content of `src/core/__tests__/assistant-manager.test.ts`:
```typescript
import { describe, it, expect, vi, beforeEach } from "vitest";
import { AssistantManager } from "../assistant/assistant-manager.js";
import { AssistantRegistry } from "../assistant/assistant-registry.js";
import type { SessionRecord } from "../types.js";
function makeRecord(sessionId: string, channelId: string): SessionRecord {
return {
sessionId,
agentSessionId: `agent-${sessionId}`,
agentName: 'claude-code',
workingDir: '/tmp',
channelId,
status: 'finished',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
isAssistant: true,
platform: {},
};
}
function mockCore(existingRecord?: SessionRecord) {
const session = {
id: existingRecord?.sessionId ?? "assistant-1",
threadId: "",
enqueuePrompt: vi.fn().mockResolvedValue(undefined),
destroy: vi.fn().mockResolvedValue(undefined),
};
const sessionStore = {
findAssistant: vi.fn().mockReturnValue(existingRecord ?? undefined),
};
return {
createSession: vi.fn().mockImplementation(async (params) => {
if (params.threadId) session.threadId = params.threadId;
if (params.existingSessionId) session.id = params.existingSessionId;
return session;
}),
connectSessionBridge: vi.fn(),
configManager: {
get: () => ({ defaultAgent: "claude-code" }),
resolveWorkspace: () => "/home/user/code",
},
sessionStore,
_session: session,
};
}
describe("AssistantManager", () => {
let registry: AssistantRegistry;
beforeEach(() => {
registry = new AssistantRegistry();
});
describe("getOrSpawn()", () => {
it("creates new session when no existing record", async () => {
const core = mockCore();
const manager = new AssistantManager(core as any, registry);
const session = await manager.getOrSpawn("telegram", "12345");
expect(core.createSession).toHaveBeenCalledWith(expect.objectContaining({
channelId: "telegram",
isAssistant: true,
initialName: "Assistant",
threadId: "12345",
}));
expect(session.threadId).toBe("12345");
expect(manager.get("telegram")).toBe(session);
});
it("reuses existing session ID when record found in store", async () => {
const existing = makeRecord("old-session-id", "telegram");
const core = mockCore(existing);
const manager = new AssistantManager(core as any, registry);
const session = await manager.getOrSpawn("telegram", "12345");
expect(core.sessionStore.findAssistant).toHaveBeenCalledWith("telegram");
expect(core.createSession).toHaveBeenCalledWith(expect.objectContaining({
existingSessionId: "old-session-id",
isAssistant: true,
channelId: "telegram",
threadId: "12345",
}));
expect(session.id).toBe("old-session-id");
});
it("second call reuses same session ID", async () => {
const core = mockCore();
const manager = new AssistantManager(core as any, registry);
// First call — no existing record
await manager.getOrSpawn("telegram", "12345");
// Now the store has the session ID
core.sessionStore.findAssistant.mockReturnValue(makeRecord("assistant-1", "telegram"));
// Second call — should reuse
await manager.getOrSpawn("telegram", "12345");
expect(core.createSession).toHaveBeenCalledTimes(2);
const secondCall = core.createSession.mock.calls[1][0];
expect(secondCall.existingSessionId).toBe("assistant-1");
});
it("stores pending system prompt after spawn", async () => {
const core = mockCore();
const manager = new AssistantManager(core as any, registry);
await manager.getOrSpawn("telegram", "12345");
const prompt = manager.consumePendingSystemPrompt("telegram");
expect(typeof prompt).toBe("string");
expect(prompt!.length).toBeGreaterThan(0);
});
});
it("get returns null for unknown channel", () => {
const core = mockCore();
const manager = new AssistantManager(core as any, registry);
expect(manager.get("discord")).toBeNull();
});
it("isAssistant returns true for assistant session", async () => {
const core = mockCore();
const manager = new AssistantManager(core as any, registry);
await manager.getOrSpawn("telegram", "12345");
expect(manager.isAssistant("assistant-1")).toBe(true);
expect(manager.isAssistant("other-session")).toBe(false);
});
});
```
- [ ] **Step 2: Run tests to verify they fail**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/__tests__/assistant-manager.test.ts 2>&1 | tail -20
```
Expected: Tests fail (`getOrSpawn is not a function`).
- [ ] **Step 3: Rewrite `assistant-manager.ts`**
Replace the entire content of `src/core/assistant/assistant-manager.ts`:
```typescript
import type { Session } from '../sessions/session.js'
import type { AssistantRegistry } from './assistant-registry.js'
import type { SessionStore } from '../sessions/session-store.js'
import { createChildLogger } from '../utils/log.js'
const log = createChildLogger({ module: 'assistant-manager' })
interface AssistantManagerCore {
createSession(params: {
channelId: string
agentName: string
workingDirectory: string
initialName?: string
isAssistant?: boolean
threadId?: string
existingSessionId?: string
}): Promise<Session>
connectSessionBridge(session: Session): void
configManager: {
get(): { defaultAgent: string }
resolveWorkspace(): string
}
sessionStore: SessionStore | null
}
export class AssistantManager {
private sessions = new Map<string, Session>()
private pendingSystemPrompts = new Map<string, string>()
constructor(
private core: AssistantManagerCore,
private registry: AssistantRegistry,
) {}
async getOrSpawn(channelId: string, threadId: string): Promise<Session> {
const existing = this.core.sessionStore?.findAssistant(channelId)
const session = await this.core.createSession({
channelId,
agentName: this.core.configManager.get().defaultAgent,
workingDirectory: this.core.configManager.resolveWorkspace(),
initialName: 'Assistant',
isAssistant: true,
threadId,
existingSessionId: existing?.sessionId,
})
this.sessions.set(channelId, session)
const systemPrompt = this.registry.buildSystemPrompt(channelId)
this.pendingSystemPrompts.set(channelId, systemPrompt)
log.info(
{ sessionId: session.id, channelId, reused: !!existing },
existing ? 'Assistant session reused (system prompt deferred)' : 'Assistant spawned (system prompt deferred)',
)
return session
}
get(channelId: string): Session | null {
return this.sessions.get(channelId) ?? null
}
/**
* Consume and return any pending system prompt for a channel.
* Should be prepended to the first real user message.
*/
consumePendingSystemPrompt(channelId: string): string | undefined {
const prompt = this.pendingSystemPrompts.get(channelId)
if (prompt) this.pendingSystemPrompts.delete(channelId)
return prompt
}
isAssistant(sessionId: string): boolean {
for (const s of this.sessions.values()) {
if (s.id === sessionId) return true
}
return false
}
}
```
- [ ] **Step 4: Run tests to verify they pass**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/__tests__/assistant-manager.test.ts 2>&1 | tail -20
```
Expected: All tests pass.
- [ ] **Step 5: Commit**
```bash
git add src/core/assistant/assistant-manager.ts src/core/__tests__/assistant-manager.test.ts
git commit -m "feat: replace spawn/respawn with getOrSpawn in AssistantManager"
```
---
### Task 6: Expose `sessionStore` on `OpenACPCore` and wire to `AssistantManager`
**Files:**
- Modify: `src/core/core.ts`
- [ ] **Step 1: Make `sessionStore` accessible**
In `src/core/core.ts`, change `private sessionStore` to public:
```typescript
// Before:
private sessionStore: SessionStore | null = null;
// After:
sessionStore: SessionStore | null = null;
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build 2>&1 | tail -30
```
Expected: Build succeeds. (The `AssistantManagerCore` interface now requires `sessionStore` — since `OpenACPCore` implements it via `this as any`, TypeScript won't enforce the interface match unless you add `sessionStore` to the interface, which was done in Task 5 step 3.)
- [ ] **Step 3: Run full test suite**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test 2>&1 | tail -30
```
Expected: All tests pass (or pre-existing failures only).
- [ ] **Step 4: Commit**
```bash
git add src/core/core.ts
git commit -m "feat: expose sessionStore publicly on OpenACPCore for AssistantManager access"
```
---
### Task 7: Update Telegram adapter to use `getOrSpawn()`
**Files:**
- Modify: `src/plugins/telegram/adapter.ts`
- [ ] **Step 1: Replace `spawn` call with `getOrSpawn`**
In `src/plugins/telegram/adapter.ts`, find (around line 688):
```typescript
await this.core.assistantManager.spawn("telegram", String(this.assistantTopicId));
```
Replace with:
```typescript
await this.core.assistantManager.getOrSpawn("telegram", String(this.assistantTopicId));
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build 2>&1 | tail -20
```
Expected: Build succeeds.
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/adapter.ts
git commit -m "feat: use getOrSpawn in Telegram adapter for persistent assistant session"
```
---
### Task 8: Remove `/clear` command
**Files:**
- Modify: `src/core/commands/session.ts`
- [ ] **Step 1: Remove the `clear` command block**
In `src/core/commands/session.ts`, remove this entire block (around lines 81-92):
```typescript
registry.register({
name: 'clear',
description: 'Clear session history',
category: 'system',
handler: async (args) => {
if (!core.assistantManager) return { type: 'error', message: 'Assistant not available' }
const assistant = core.assistantManager.get(args.channelId)
if (!assistant) return { type: 'error', message: 'No assistant session for this channel.' }
await core.assistantManager.respawn(args.channelId, assistant.threadId)
return { type: 'text', text: '✅ Assistant history cleared.' }
},
})
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build 2>&1 | tail -20
```
Expected: Build succeeds.
- [ ] **Step 3: Run commands test to verify**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test src/core/commands/__tests__/commands.test.ts 2>&1 | tail -20
```
Expected: Tests pass (or update any test that checks for `/clear` command).
- [ ] **Step 4: Commit**
```bash
git add src/core/commands/session.ts
git commit -m "feat: remove /clear command for assistant (no longer needed)"
```
---
### Task 9: Final verification
- [ ] **Step 1: Run full test suite**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test 2>&1 | tail -40
```
Expected: All tests pass (or only pre-existing failures).
- [ ] **Step 2: Build production bundle**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build 2>&1 | tail -10
```
Expected: Build succeeds with no errors.
- [ ] **Step 3: Final commit (if anything was missed)**
If there are any unstaged changes, commit them.
```bash
git add -p # review each change
git commit -m "chore: persistent assistant session final cleanup"
```

View File

@ -1,550 +0,0 @@
# Telegram Custom Path Wizard Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace AI-assistant delegation for the "Custom path" button in the Telegram new-session wizard with a Force Reply flow that validates the workspace path immediately using pure logic.
**Architecture:** When a user clicks "Custom path", the bot sends a Telegram Force Reply message (which auto-opens a reply box in the user's app). When the user replies, the path is validated with `core.configManager.resolveWorkspace()`. On error, an error message is shown and a new Force Reply is sent. On success, `createSessionDirect()` is called. State is tracked in a module-level Map keyed by the Force Reply message ID, with a 10-minute TTL.
**Tech Stack:** TypeScript, grammY (Telegram bot framework), Vitest
---
## File Structure
| File | Change |
|---|---|
| `src/plugins/telegram/commands/new-session.ts` | Add `forceReplyMap` state, `sendCustomPathPrompt()`, `handleCustomPathReply()`, replace `ns:custom:` body, register `message:text` interceptor |
| `src/plugins/telegram/commands/__tests__/custom-path-wizard.test.ts` | New: unit tests for the wizard logic |
---
### Task 1: Write failing tests for force-reply state management
**Files:**
- Create: `src/plugins/telegram/commands/__tests__/custom-path-wizard.test.ts`
- [ ] **Step 1: Create the test file**
```typescript
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// We will import these once they are exported from new-session.ts in Task 2
import {
_forceReplyMap,
_pruneExpiredForceReplies,
_handleCustomPathReply,
_sendCustomPathPrompt,
} from "../new-session.js";
// ── Helpers ──────────────────────────────────────────────────────────
function makeCtx(overrides: Partial<{
messageId: number;
replyToMessageId: number | undefined;
text: string;
threadId: number | undefined;
chatId: number;
}> = {}) {
const opts = {
messageId: 1,
replyToMessageId: undefined,
text: "~/my-project",
threadId: undefined,
chatId: 42,
...overrides,
};
const ctx = {
message: {
message_id: opts.messageId,
text: opts.text,
message_thread_id: opts.threadId,
reply_to_message: opts.replyToMessageId
? { message_id: opts.replyToMessageId }
: undefined,
},
callbackQuery: undefined,
from: { id: 1 },
api: {
// Full mock of Telegram API methods used by createSessionDirect
sendMessage: vi.fn().mockResolvedValue({ message_id: 100 }),
createForumTopic: vi.fn().mockResolvedValue({ message_thread_id: 99 }),
editForumTopic: vi.fn().mockResolvedValue({}),
deleteForumTopic: vi.fn().mockResolvedValue({}),
},
reply: vi.fn().mockResolvedValue({ message_id: 200 }),
};
return ctx as unknown as import("grammy").Context;
}
function makeCore(overrides: { resolveWorkspace?: (input?: string) => string } = {}) {
return {
configManager: {
resolveWorkspace: vi.fn((input?: string) => {
if (overrides.resolveWorkspace) return overrides.resolveWorkspace(input);
// Default: expand ~/my-project to absolute path
if (input?.startsWith("~/")) return `/home/user/${input.slice(2)}`;
if (input?.startsWith("/")) return input;
if (/^[a-z0-9_-]+$/i.test(input ?? "")) return `/home/user/openacp-workspace/${input}`;
throw new Error(`Invalid workspace name: "${input}". Only alphanumeric characters, hyphens, and underscores are allowed.`);
}),
},
handleNewSession: vi.fn().mockResolvedValue({
id: "sess-1",
agentName: "claude",
workingDirectory: "/home/user/my-project",
}),
} as unknown as import("../../../../core/index.js").OpenACPCore;
}
// ── Tests ──────────────────────────────────────────────────────────
describe("forceReplyMap TTL pruning", () => {
beforeEach(() => _forceReplyMap.clear());
it("prunes entries older than 10 minutes", () => {
const OLD = Date.now() - 11 * 60 * 1000;
const FRESH = Date.now() - 1 * 60 * 1000;
_forceReplyMap.set(1, { agentKey: "claude", chatId: 42, createdAt: OLD });
_forceReplyMap.set(2, { agentKey: "gemini", chatId: 42, createdAt: FRESH });
_pruneExpiredForceReplies();
expect(_forceReplyMap.has(1)).toBe(false);
expect(_forceReplyMap.has(2)).toBe(true);
});
it("leaves empty map intact", () => {
_pruneExpiredForceReplies();
expect(_forceReplyMap.size).toBe(0);
});
});
describe("_sendCustomPathPrompt", () => {
beforeEach(() => _forceReplyMap.clear());
it("sends a force_reply message and stores entry in forceReplyMap", async () => {
const ctx = makeCtx({ chatId: 42, threadId: 5 });
await _sendCustomPathPrompt(ctx, 42, "claude");
expect(ctx.api.sendMessage).toHaveBeenCalledOnce();
const [callChatId, callText, callOpts] = (ctx.api.sendMessage as ReturnType<typeof vi.fn>).mock.calls[0];
expect(callChatId).toBe(42);
expect(callText).toContain("workspace path");
expect((callOpts as any).reply_markup).toEqual({ force_reply: true, selective: true });
expect((callOpts as any).message_thread_id).toBe(5);
// Entry stored in map
expect(_forceReplyMap.size).toBe(1);
const entry = [..._forceReplyMap.values()][0];
expect(entry.agentKey).toBe("claude");
expect(entry.chatId).toBe(42);
expect(entry.createdAt).toBeGreaterThan(0);
});
it("sends without thread_id when not in a topic", async () => {
const ctx = makeCtx({ chatId: 42, threadId: undefined });
await _sendCustomPathPrompt(ctx, 42, "claude");
const callOpts = (ctx.api.sendMessage as ReturnType<typeof vi.fn>).mock.calls[0][2];
expect((callOpts as any).message_thread_id).toBeUndefined();
});
});
describe("_handleCustomPathReply", () => {
beforeEach(() => _forceReplyMap.clear());
it("calls resolveWorkspace and does not send error reply on valid input", async () => {
const ctx = makeCtx({ text: "~/my-project", chatId: 42 });
const core = makeCore();
const entry = { agentKey: "claude", chatId: 42, createdAt: Date.now() };
await _handleCustomPathReply(ctx, core, 42, entry);
// resolveWorkspace was called with trimmed input
expect(core.configManager.resolveWorkspace).toHaveBeenCalledWith("~/my-project");
// No error reply sent
const replyArg = (ctx.reply as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as string | undefined;
expect(replyArg).not.toContain("❌");
});
it("shows error and sends new force_reply on invalid path", async () => {
const ctx = makeCtx({ text: "bad path!", chatId: 42 });
const core = makeCore({
resolveWorkspace: () => { throw new Error('Invalid workspace name: "bad path!". Only alphanumeric characters, hyphens, and underscores are allowed.'); },
});
const entry = { agentKey: "claude", chatId: 42, createdAt: Date.now() };
await _handleCustomPathReply(ctx, core, 42, entry);
// Should show error
expect(ctx.reply).toHaveBeenCalledOnce();
const errorText = (ctx.reply as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(errorText).toContain("❌");
expect(errorText).toContain("Invalid workspace name");
// Should send new force_reply
expect(ctx.api.sendMessage).toHaveBeenCalledOnce();
const sendOpts = (ctx.api.sendMessage as ReturnType<typeof vi.fn>).mock.calls[0][2];
expect((sendOpts as any).reply_markup).toEqual({ force_reply: true, selective: true });
// New entry stored in map
expect(_forceReplyMap.size).toBe(1);
});
it("does NOT call ctx.api.createForumTopic on invalid path", async () => {
const ctx = makeCtx({ text: "bad path!", chatId: 42 });
const core = makeCore({
resolveWorkspace: () => { throw new Error("Workspace path does not exist."); },
});
const entry = { agentKey: "claude", chatId: 42, createdAt: Date.now() };
await _handleCustomPathReply(ctx, core, 42, entry);
// createSessionDirect was never reached (no forum topic created)
expect((ctx.api as any).createForumTopic).not.toHaveBeenCalled();
});
});
```
- [ ] **Step 2: Run tests to verify they fail (module not found)**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/plugins/telegram/commands/__tests__/custom-path-wizard.test.ts 2>&1 | head -30
```
Expected: FAIL — `_forceReplyMap`, `_pruneExpiredForceReplies`, etc. are not exported from `new-session.ts`
---
### Task 2: Add state and helper functions to `new-session.ts`
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts`
- [ ] **Step 1: Add `ForceReplyEntry` interface and `forceReplyMap` state after the existing `workspaceCache` block (after line ~226)**
Insert after `let nextWsId = 0` (line 206), before `function cacheWorkspace`:
```typescript
// --- Force Reply state for custom path input ---
interface ForceReplyEntry {
agentKey: string;
chatId: number;
createdAt: number; // ms timestamp, for TTL
}
export const _forceReplyMap = new Map<number, ForceReplyEntry>();
export function _pruneExpiredForceReplies(): void {
const cutoff = Date.now() - 10 * 60 * 1000;
for (const [msgId, entry] of _forceReplyMap) {
if (entry.createdAt < cutoff) _forceReplyMap.delete(msgId);
}
}
```
- [ ] **Step 2: Add `_sendCustomPathPrompt()` function after `_pruneExpiredForceReplies`**
```typescript
export async function _sendCustomPathPrompt(
ctx: Context,
chatId: number,
agentKey: string,
): Promise<void> {
const threadId =
ctx.message?.message_thread_id ??
(ctx as Context & { callbackQuery?: { message?: { message_thread_id?: number } } })
.callbackQuery?.message?.message_thread_id;
const sent = await ctx.api.sendMessage(
chatId,
`Please type the workspace path.\n\n` +
`Examples:\n` +
`• <code>/absolute/path/to/project</code>\n` +
`• <code>~/my-project</code>\n` +
`• <code>project-name</code> (created under your base directory)\n\n` +
`Reply to this message with your path.`,
{
parse_mode: 'HTML',
reply_markup: { force_reply: true, selective: true },
...(threadId !== undefined ? { message_thread_id: threadId } : {}),
},
);
_forceReplyMap.set(sent.message_id, { agentKey, chatId, createdAt: Date.now() });
}
```
- [ ] **Step 3: Add `_handleCustomPathReply()` function after `_sendCustomPathPrompt`**
```typescript
export async function _handleCustomPathReply(
ctx: Context,
core: OpenACPCore,
chatId: number,
entry: ForceReplyEntry,
): Promise<void> {
const input = ctx.message!.text.trim();
let resolvedPath: string;
try {
resolvedPath = core.configManager.resolveWorkspace(input);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await ctx.reply(`❌ ${escapeHtml(message)}\n\nPlease try again:`, {
parse_mode: 'HTML',
}).catch(() => {});
await _sendCustomPathPrompt(ctx, chatId, entry.agentKey);
return;
}
await createSessionDirect(ctx, core, chatId, entry.agentKey, resolvedPath);
}
```
- [ ] **Step 4: Run the tests — they should now pass**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test src/plugins/telegram/commands/__tests__/custom-path-wizard.test.ts
```
Expected: all tests PASS
- [ ] **Step 5: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts src/plugins/telegram/commands/__tests__/custom-path-wizard.test.ts
git commit -m "feat: add force-reply state helpers for telegram custom path wizard"
```
---
### Task 3: Replace `ns:custom:` callback body with Force Reply
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts` lines 373–398
- [ ] **Step 1: Replace the `ns:custom:` callback handler body**
Find this block in `setupNewSessionCallbacks` (currently lines 373–398):
```typescript
bot.callbackQuery(/^ns:custom:/, async (ctx) => {
const agentKey = ctx.callbackQuery.data.replace('ns:custom:', '')
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
const assistant = getAssistantSession?.()
if (assistant) {
try {
await ctx.editMessageText(
`<b>🆕 New Session</b>\n` +
`Agent: <code>${escapeHtml(agentKey)}</code>\n\n` +
`💬 Type your workspace path in the chat below.`,
{ parse_mode: 'HTML' },
)
} catch { /* ignore */ }
await assistant.enqueuePrompt(
`User wants to create a new session with agent "${agentKey}". Ask them for the workspace (project directory) path, then create the session.`
)
} else {
try {
await ctx.editMessageText(
`Usage: <code>/new ${escapeHtml(agentKey)} &lt;workspace-path&gt;</code>`,
{ parse_mode: 'HTML' },
)
} catch { /* ignore */ }
}
})
```
Replace with:
```typescript
bot.callbackQuery(/^ns:custom:/, async (ctx) => {
const agentKey = ctx.callbackQuery.data.replace('ns:custom:', '')
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
// Remove inline keyboard from wizard message so user can't click stale buttons
try {
await ctx.editMessageText(
`<b>🆕 New Session</b>\n` +
`Agent: <code>${escapeHtml(agentKey)}</code>\n\n` +
`⌨️ Waiting for workspace path...`,
{ parse_mode: 'HTML' },
)
} catch { /* ignore */ }
await _sendCustomPathPrompt(ctx, chatId, agentKey)
})
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds with no errors
- [ ] **Step 3: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 4: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts
git commit -m "feat: replace ns:custom AI delegation with force-reply path input"
```
---
### Task 4: Register force-reply interceptor in `setupNewSessionCallbacks`
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts`
The interceptor must be registered **inside `setupNewSessionCallbacks`** so it runs before the terminal `setupRoutes()` message handler in `adapter.ts`. It intercepts `message:text` events where the message is a reply to a known force-reply message, processes the path, and calls `next()` otherwise.
- [ ] **Step 1: Add `bot.on("message:text")` interceptor at the top of `setupNewSessionCallbacks`**
Insert as the **first** handler inside `setupNewSessionCallbacks` (before the `bot.callbackQuery('ns:start', ...)` line):
```typescript
// Intercept replies to force-reply messages (custom path input)
bot.on("message:text", async (ctx, next) => {
_pruneExpiredForceReplies()
const replyToId = ctx.message.reply_to_message?.message_id
if (replyToId === undefined) return next()
const entry = _forceReplyMap.get(replyToId)
if (!entry) return next()
_forceReplyMap.delete(replyToId)
await _handleCustomPathReply(ctx, core, chatId, entry)
})
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds
- [ ] **Step 3: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 4: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts
git commit -m "feat: register force-reply interceptor for custom path wizard"
```
---
### Task 5: Remove `getAssistantSession` parameter dependency from `setupNewSessionCallbacks`
The `getAssistantSession` parameter in `setupNewSessionCallbacks` was only used by the `ns:custom:` callback body (now replaced). Clean it up to keep the signature lean.
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts`
- Modify: `src/plugins/telegram/commands/index.ts` (call site)
- [ ] **Step 1: Check if `getAssistantSession` is used anywhere else in `setupNewSessionCallbacks`**
```bash
grep -n "getAssistantSession\|assistant\." /Users/lucas/code/openacp-workspace/OpenACP/src/plugins/telegram/commands/new-session.ts
```
Expected: the only usage was in the old `ns:custom:` body. If any other usages appear, skip this task.
- [ ] **Step 2: Remove `getAssistantSession` parameter from `setupNewSessionCallbacks` (only if Step 1 confirms no other usage)**
Change the function signature from:
```typescript
export function setupNewSessionCallbacks(
bot: Bot,
core: OpenACPCore,
chatId: number,
getAssistantSession?: () => { topicId: number; enqueuePrompt: (p: string) => Promise<string> } | undefined,
): void {
```
To:
```typescript
export function setupNewSessionCallbacks(
bot: Bot,
core: OpenACPCore,
chatId: number,
): void {
```
- [ ] **Step 3: Update the call site in `commands/index.ts`**
In `setupAllCallbacks`, change:
```typescript
setupNewSessionCallbacks(bot, core, chatId, getAssistantSession);
```
To:
```typescript
setupNewSessionCallbacks(bot, core, chatId);
```
- [ ] **Step 4: Update the import in `commands/index.ts` if `getAssistantSession` type is no longer needed there**
The `getAssistantSession` parameter in `setupAllCallbacks` itself is still used by other handlers (e.g., `setupSettingsCallbacks`), so leave the outer signature intact.
- [ ] **Step 5: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds
- [ ] **Step 6: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 7: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts src/plugins/telegram/commands/index.ts
git commit -m "refactor: remove getAssistantSession param from setupNewSessionCallbacks"
```

View File

@ -1,374 +0,0 @@
# Codebase Logic Review — Findings
**Date:** 2026-03-27
**Scope:** Full codebase review — core, plugins, adapter primitives, utilities
**Status:** Review complete — awaiting triage
---
## Previously Identified Issues (from spec) — All Fixed
The 7 issues from `2026-03-27-codebase-logic-review-design.md` have all been implemented:
1. PermissionGate `setPending()` superseding — fixed
2. AgentInstance `destroy()` waiting for exit — fixed
3. SessionBridge `handleAgentEvent()` error handling — fixed
4. CommandRegistry `unregister()` dead code — fixed
5. MiddlewareChain pre-sorted at `add()` time — fixed
6. AgentInstance crash detection for signal kills — fixed
7. NotificationManager error catching — fixed
---
## New Issues Found
### HIGH Severity
#### H1. Session `processPrompt` throws unrecoverably if session is "finished"
**File:** `src/core/sessions/session.ts:179-181`
**Issue:** If a session is in "finished" state and a queued prompt still executes (enqueued just before `finish()` was called), `this.activate()` throws because `finished -> active` is invalid. The PromptQueue error handler calls `session.fail()`, but `finished -> error` is also invalid — causing a **second throw** that becomes an unhandled exception.
**Fix:** Guard at top of `processPrompt`:
```typescript
if (this._status === "finished") return;
```
---
#### H2. `cancelSession` can throw if agent error transitions state before `markCancelled()`
**File:** `src/core/sessions/session-manager.ts:118-122`
**Issue:** `session.abortPrompt()` can trigger the agent to emit an error, calling `session.fail()` which transitions to "error" state. Then `markCancelled()` attempts `error -> cancelled`, which is invalid in the state machine (`error` can only go to `active`). This throws an uncaught exception.
**Fix:** Either:
- Add "cancelled" to valid transitions from "error" state
- Wrap `markCancelled()` in try-catch
- Check session status before calling `markCancelled()`
---
#### H3. ConfigManager `save()` writes invalid config to disk, bricks next startup
**File:** `src/core/config/config.ts:260-283`
**Issue:** `save()` writes the merged config to disk **before** re-validating with Zod. If validation fails, the invalid config is already on disk. Next startup reads this invalid config and calls `process.exit(1)`.
**Fix:** Validate BEFORE writing to disk. If validation fails, log an error and don't write.
---
#### H4. Session logger leaks file descriptors — `pino.destination` never closed
**File:** `src/core/utils/log.ts:160-210`
**Issue:** Each session creates a `pino.destination(sessionLogPath)` which opens a file descriptor. The destination is stored as `__sessionDest` but never closed. Long-running servers with many sessions will exhaust OS file descriptor limits.
**Fix:** Add a `closeSessionLogger()` function called during `session.destroy()`:
```typescript
export function closeSessionLogger(logger: Logger): void {
const dest = (logger as any).__sessionDest
if (dest && typeof dest.destroy === 'function') {
dest.destroy()
}
}
```
---
#### H5. ActivityTracker: thinking indicator stuck when `maxThinkingDuration` exceeded
**File:** `src/core/adapter-primitives/primitives/activity-tracker.ts:74-76`
**Issue:** When `maxThinkingDuration` is exceeded, `stopRefresh` is called (stops the interval timer), but `removeThinkingIndicator()` is **never called**. The thinking indicator remains visible to the user indefinitely.
**Fix:**
```typescript
if (Date.now() - state.startTime >= this.config.maxThinkingDuration) {
state.dismissed = true
this.stopRefresh(state)
state.callbacks.removeThinkingIndicator().catch(() => {})
return
}
```
---
#### H6. `main.ts`: spinner/logger not cleaned up on plugin boot failure
**File:** `src/main.ts:119-272`
**Issue:** If `core.lifecycleManager.boot()` throws, the spinner keeps spinning and logger stays muted (from `muteLogger()`). The error catch at line 270 logs the error, but the muted logger swallows it. The user sees a spinning animation and no error message, then `process.exit(1)`.
**Fix:** Stop spinner and unmute logger in the catch block:
```typescript
} catch (err) {
if (spinner) spinner.fail('Plugin boot failed')
unmuteLogger()
log.error({ err }, 'Plugin boot failed')
}
```
---
### MEDIUM Severity
#### M1. Agent crash during auto-naming silently discards error event
**File:** `src/core/sessions/session.ts:363-396`
**Issue:** During `autoName()`, the session emitter is paused and a capture handler only catches "text" events (line 370). If the agent crashes during auto-naming, the crash error event is buffered. Then `clearBuffer()` at line 393 **discards all buffered events**, including the crash error. The user never sees the crash notification.
**Fix:** In `autoName()` finally block, replay error-type events instead of clearing all:
```typescript
// Replay error events, discard others
const buffer = this.getBuffer() // need to expose buffer
for (const { event, args } of buffer) {
if (event === 'agent_event') {
const agentEvent = args[0] as AgentEvent
if (agentEvent?.type === 'error') {
this.emit('agent_event', agentEvent)
}
}
}
this.clearBuffer()
this.resume()
```
---
#### M2. PermissionGate timeout timer not `unref()`ed — blocks graceful shutdown
**File:** `src/core/sessions/permission-gate.ts:33-36`
**Issue:** The 10-minute timeout timer keeps the Node.js event loop alive. During graceful shutdown with an active permission request, the process won't exit for up to 10 minutes.
**Fix:** Add `unref()` after setting the timer (pattern already used in `agent-instance.ts:753`):
```typescript
this.timeoutTimer = setTimeout(() => {
this.reject("Permission request timed out");
}, this.timeoutMs);
if (typeof this.timeoutTimer === 'object' && 'unref' in this.timeoutTimer) {
(this.timeoutTimer as NodeJS.Timeout).unref();
}
```
---
#### M3. Lazy resume resurrects truly-finished sessions after restart
**File:** `src/core/core.ts:603-688`
**Issue:** On shutdown, ALL sessions are marked as `status: "finished"` in `shutdownAll()`. On restart, when a user messages in a thread of a truly-completed session, `lazyResume` spawns a new agent for it. The user may not expect their completed session to restart.
**Fix:** Either:
- Skip `status === "finished"` in `lazyResume`
- Use a separate status like `"shutdown"` for sessions that were active at shutdown time
---
#### M4. `SessionBridge.sendMessage` — middleware errors become unhandled rejections
**File:** `src/core/sessions/session-bridge.ts:40-53`
**Issue:** `sendMessage` is async but called without `await` in `handleAgentEvent`. The `mw.execute()` call is awaited within `sendMessage`, and if middleware throws, it propagates as an unhandled promise rejection.
**Fix:** Add `.catch()` to `sendMessage` calls in `handleAgentEvent`, or wrap the entire `sendMessage` body in try-catch.
---
#### M5. `handleCleanup` doesn't cancel active sessions before deleting records
**File:** `src/plugins/telegram/commands/session.ts:167-201`
**Issue:** `handleCleanup` deletes session records without first cancelling running agent processes. Compare with `handleCleanupEverythingConfirmed` which correctly calls `cancelSession` before removal. This can orphan running agent subprocesses.
**Fix:** Add active session cancellation before record removal, similar to `handleCleanupEverythingConfirmed`.
---
#### M6. Tunnel providers don't wait for child process exit on `stop()`
**Files:** All tunnel providers (`cloudflare.ts`, `ngrok.ts`, `bore.ts`, `tailscale.ts`)
**Issue:** All providers call `this.child.kill('SIGTERM')` and immediately set `this.child = null` without waiting for exit. If a new tunnel is started immediately on the same port, the old process may still be holding it.
**Fix:** Wait for the `exit` event with a SIGKILL timeout fallback.
---
#### M7. `CheckpointReader` uses `execFileSync` blocking the event loop
**File:** `src/plugins/context/entire/checkpoint-reader.ts:43-51`
**Issue:** The `git()` method uses `execFileSync`, blocking the Node.js event loop. `resolveLatest` iterates all checkpoints with synchronous git calls. Repositories with many checkpoints can freeze all operations for seconds.
**Fix:** Use `execFile` with `util.promisify` instead of `execFileSync`.
---
#### M8. `PermissionHandler` pending map grows unboundedly (memory leak)
**File:** `src/plugins/telegram/permissions.ts:18, 32`
**Issue:** The `pending` Map stores entries for every permission request sent. Entries are only removed when the user clicks a button. If ignored, entries stay in memory forever.
**Fix:** Add TTL-based cleanup (e.g., remove entries older than 10 minutes).
---
#### M9. `createBridge` throws if notification/file-service plugins not loaded
**File:** `src/core/core.ts:693-702`
**Issue:** `createBridge()` accesses `this.notificationManager` and `this.fileService` via `getService()` which throws if not registered. If these plugins failed to load, all session creation crashes.
**Fix:** Use optional service lookups that return `undefined` instead of throwing.
---
#### M10. Draft `flush()` race condition — concurrent flushes can create duplicate messages
**File:** `src/core/adapter-primitives/primitives/draft-manager.ts:59-79`
**Issue:** `finalize()` awaits `flushPromise` then calls `flush()`, but a timer-triggered flush can sneak in between. If both are first-flushes (no `_messageId` yet), both create separate messages.
**Fix:** Chain the finalize flush onto `flushPromise`:
```typescript
this.flushPromise = this.flushPromise.then(() => this.buffer ? this.flush() : undefined)
await this.flushPromise
```
---
#### M11. Node stream adapters don't implement close/cancel — resource leaks
**File:** `src/core/utils/streams.ts:3-26`
**Issue:** `nodeToWebWritable` doesn't implement `close()` or `abort()`. `nodeToWebReadable` doesn't implement `cancel()`. When Web streams are closed/cancelled, the underlying Node streams stay open, leaking file handles/sockets.
**Fix:** Add the missing handlers:
```typescript
// WritableStream
close() { nodeStream.end() },
abort(reason) { nodeStream.destroy(reason instanceof Error ? reason : new Error(String(reason))) }
// ReadableStream
cancel() { nodeStream.destroy() }
```
---
### LOW Severity
#### L1. `SecurityGuard.checkAccess` TOCTOU race on session count
**File:** `src/plugins/security/security-guard.ts:22-27`
**Issue:** Session count checked at access time, but session created after check passes. Two concurrent messages can both pass the check, exceeding `maxConcurrentSessions` by 1.
**Verdict:** Acceptable for current use case. Note if session limits become critical.
---
#### L2. `core.ts` `patchRecord` not awaited — potential unhandled rejection
**File:** `src/core/core.ts:293-295`
**Issue:** `patchRecord` returns Promise but is not awaited. Store write failures become unhandled rejections.
**Fix:** Add `.catch()` or await.
---
#### L3. PluginContext `cleanup()` service unregistration order
**File:** `src/core/plugin/plugin-context.ts:179-200`
**Issue:** Services are unregistered (line 190) before command registry is accessed (line 193). If the command-registry was registered by the same plugin being cleaned up, commands are never cleaned.
**Fix:** Move command cleanup before service unregistration.
---
#### L4. SendQueue timer not cleared on `clear()` — temporary message stall
**File:** `src/core/adapter-primitives/primitives/send-queue.ts:85-106`
**Issue:** `clear()` doesn't cancel the pending setTimeout. New items enqueued between `clear()` and the timer firing won't be processed until the orphaned timer fires.
**Fix:** Track and clear the timer in `clear()`.
---
#### L5. `downloadFile` unlimited redirect following
**File:** `src/core/utils/install-binary.ts:24-64`
**Issue:** Follows 301/302 redirects recursively with no limit. A misconfigured server could cause stack overflow.
**Fix:** Add `maxRedirects` parameter (default 10).
---
#### L6. `main.ts` `fs.watch` watcher never closed on shutdown
**File:** `src/main.ts:224-243`
**Issue:** Dev plugin hot-reload watcher is never stored or closed during shutdown. Keeps process alive or causes errors after cleanup.
**Fix:** Store the watcher and close it during shutdown.
---
#### L7. `SpeechService.refreshProviders` doesn't remove stale factory providers
**File:** `src/plugins/speech/speech-service.ts:68-80`
**Issue:** When config changes remove a provider, the old factory-created provider remains registered. Merge only adds/overwrites, never removes factory providers.
**Fix:** Track factory-created vs externally-registered providers. Clear factory providers before re-adding.
---
#### L8. `ContextCache` constructor creates directory synchronously — crashes on permission error
**File:** `src/plugins/context/context-cache.ts:10`
**Issue:** `fs.mkdirSync` in constructor throws synchronously on permission errors, crashing the application during plugin boot.
**Fix:** Wrap in try-catch or defer to first use.
---
#### L9. PromptQueue race — enqueue during `clear()` can bypass the clear
**File:** `src/core/sessions/prompt-queue.ts:55-65`
**Issue:** Narrow window where `enqueue()` between `clear()` resolving pending items and `finally` block running `drainNext()` causes a prompt to execute after cancel was requested.
**Fix:** Add a generation counter checked in `drainNext()`.
---
## Summary by Priority
| Priority | Count | Issues |
|----------|-------|--------|
| **HIGH** | 6 | H1, H2, H3, H4, H5, H6 |
| **MEDIUM** | 11 | M1-M11 |
| **LOW** | 9 | L1-L9 |
### Recommended Fix Order
1. **H1** — Session processPrompt finished-state crash (trivial 1-line guard)
2. **H2** — cancelSession state machine throw (add valid transition or guard)
3. **H5** — Thinking indicator stuck forever (3-line fix)
4. **H6** — Boot failure invisible to user (add spinner/unmute cleanup)
5. **H3** — Config save bricks startup (validate before write)
6. **H4** — Session logger fd leak (add close function)
7. **M2** — PermissionGate timer unref (2-line fix)
8. **M4** — sendMessage unhandled rejections (add .catch())
9. **M1** — Auto-name swallows crash errors (replay errors from buffer)
10. Rest of MEDIUM/LOW based on impact

View File

@ -1,113 +0,0 @@
# One-Liner Install Script — Design Spec
## Overview
Add one-liner install scripts (`install.sh` for macOS/Linux, `install.ps1` for Windows) that automatically detect the environment, install Node.js if missing, install `@openacp/cli` via npm, and launch the setup wizard. This removes the npm knowledge barrier for non-developer users.
**Motivation:** Current installation requires users to know npm (`npm install -g @openacp/cli`). Non-dev users don't know what npm is. Industry standard for CLI tools provides one-liner curl/PowerShell commands that handle everything automatically.
## One-Liner Commands
```bash
# macOS/Linux
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
# Windows
powershell -c "irm https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.ps1 | iex"
```
Future: redirect via custom domain (e.g., `openacp.dev/install.sh`) when available.
## install.sh (macOS/Linux) — ~800-1000 lines
### Flow
1. **Banner + branding** — ANSI colors, OpenACP tagline
2. **Detect environment** — OS (Darwin/Linux), arch (x86_64/arm64), downloader (curl/wget)
3. **Bootstrap gum** — Download [charmbracelet/gum](https://github.com/charmbracelet/gum) to temp dir for fancy terminal UI (spinners, confirm dialogs, select menus). Verify SHA256. Fallback to plain text if download fails. Cleaned up on exit.
4. **Parse CLI flags:**
- `--version <tag>` — npm install target (default: `latest`; use `main` for GitHub main branch)
- `--install-method npm|git` — npm (default) or clone+build
- `--no-onboard` — skip running `openacp` after install
- `--dry-run` — print actions without executing
- `--verify` — verify installation after completion
5. **Choose install method** — Interactive (gum choose) if TTY, default to npm otherwise
6. **Check/install Node.js ≥22:**
- Detect existing: `node` on PATH, nvm, nodenv, Homebrew, system package
- If version too old: guide user to upgrade (nvm instructions if nvm detected)
- If missing: download NodeSource official binary (tar.gz from nodejs.org), verify SHA256, install to user-local path
- Handle npm prefix/PATH issues (EACCES → setup `~/.npm-global`)
7. **Install @openacp/cli:**
- **npm method:** `npm install -g @openacp/cli@<version>` with retry logic, log capture on failure
- **git method:** clone repo, install pnpm, `pnpm install`, `pnpm build`, create wrapper script in `~/.local/bin`
8. **Verify install** — Run `openacp --version` to confirm
9. **Post-install:**
- If TTY available → `exec openacp` (launches setup wizard directly)
- If no TTY → print instruction: `Run 'openacp' to complete setup`
### Key Features
- **gum UI:** Spinner animations, colored output, interactive menus via charmbracelet/gum (temp binary, auto-cleaned)
- **SHA256 verification:** Both gum binary and Node.js binary verified via checksums
- **Retry logic:** npm install retries on transient failures
- **sudo detection:** Avoid running as root when not needed, handle EACCES gracefully
- **nvm/nodenv awareness:** Detect managed Node.js, provide upgrade instructions instead of conflicting install
- **Temp file cleanup:** Trap EXIT to clean up all temp files/dirs
- **Non-interactive mode:** Detect piped input, skip interactive prompts, use defaults
## install.ps1 (Windows) — ~300 lines
### Flow
1. **Banner** — ANSI colors (PowerShell escape sequences)
2. **Check/fix execution policy** — Set RemoteSigned for current process if Restricted
3. **Check/install Node.js ≥22:** Try `winget` → `choco` → `scoop` → fail with manual instructions (nodejs.org link)
4. **Check/install Git** — Required for npm; try winget, fail with manual link
5. **Install @openacp/cli** — `npm install -g @openacp/cli` with error handling
6. **PATH setup** — Add npm global bin to user PATH
7. **Post-install** — Run `openacp` if TTY, else print instructions
### Parameters
```powershell
param(
[string]$InstallMethod = "npm",
[string]$Tag = "latest",
[string]$GitDir = "$env:USERPROFILE\openacp",
[switch]$NoOnboard,
[switch]$NoGitUpdate,
[switch]$DryRun
)
```
No gum on Windows. Plain text with ANSI colors only.
## Config
No config changes required. The install scripts install the existing `@openacp/cli` package which has its own setup wizard.
## Node.js Requirements
- Minimum: Node.js ≥22
- Default install target: Node.js 24 (LTS)
- Version detection parses `node --version` output
## Files
| File | Action |
|------|--------|
| `scripts/install.sh` | New — macOS/Linux one-liner installer |
| `scripts/install.ps1` | New — Windows PowerShell installer |
| `README.md` | Modified — add one-liner Quick Start section above existing npm instructions |
| `docs/` | Modified — add installation guide with all methods |
## Testing
- `--dry-run` flag for testing logic without side effects
- `--verify` flag for post-install verification
- Docker-based testing for install.sh (Ubuntu, Debian, Alpine)
- Manual testing on macOS and Windows PowerShell
## Backward Compatibility
No breaking changes. Existing `npm install -g @openacp/cli` method continues to work. One-liner scripts are an additional installation path that ultimately runs the same npm install.

View File

@ -1,293 +0,0 @@
# Agent Switch — Design Spec
> Switch agents mid-session while preserving conversation context and session continuity.
## Overview
Allow users to switch between agents (e.g., Claude → Gemini) within the same OpenACP session. The system session remains intact — same session ID, same platform thread — only the underlying agent instance is swapped. Conversation history is injected into the new agent so it has full context.
When switching back to a previously used agent, the system can **resume** that agent's session if no user prompts were sent during the interim agent's turn and the agent supports resume. Otherwise, a new agent session is created with history injection.
## Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Old agent subprocess | Kill immediately on switch | ACP `unstable_resumeSession` re-spawns when needed; saves resources |
| History scope | Full history with optional agent labels | New agent needs complete context; labels are configurable |
| Resume condition | `promptCount === 0` + agent supports resume | Only system messages (context injection, welcome) don't count; user prompts do |
| Prompt counting | Exclude first context injection prompt | System-generated messages don't indicate user interaction |
| In-flight prompt handling | Confirm with user before cancel | Prevent accidental data loss |
| Architecture approach | Session-level switch (swap agent instance in place) | Simplest; session ID + thread unchanged; good foundation for future fork |
| Command UX | `/switch` (menu) + `/switch <agent>` (direct) | Power users use direct, casual users use menu |
| Label setting | Both config + `/switch label on/off` | Accessible from both places |
| Middleware hooks | `agent:beforeSwitch` (blocking) + `agent:afterSwitch` (fire-and-forget) | Sufficient for security, usage tracking, etc. |
## Data Model
### SessionRecord extensions
```typescript
interface AgentSwitchEntry {
agentName: string;
agentSessionId: string;
switchedAt: string; // ISO timestamp
promptCount: number; // user prompts only (excludes system messages)
}
interface SessionRecord {
// ... existing fields ...
firstAgent: string; // agent used when session was created
currentPromptCount: number; // prompt count for current agent turn (persisted for restart recovery)
agentSwitchHistory: AgentSwitchEntry[]; // newest entry at end
}
```
### Backward compatibility
- `firstAgent`: defaults to current `agentName` for existing sessions
- `agentSwitchHistory`: defaults to `[]` for existing sessions
- Old sessions without these fields continue working unchanged
### Resumable (derived at runtime)
```typescript
function canResume(entry: AgentSwitchEntry, agentDef: AgentDefinition): boolean {
return entry.promptCount === 0 && agentDef.supportsResume;
}
```
## Switch Flow
### Happy path: Claude → Gemini (new session)
```
1. User sends /switch gemini
2. Check prompt in-flight → if yes, confirm "Cancel and switch?" [Yes] [No]
3. Middleware: agent:beforeSwitch (plugins can block)
4. Save current agent to switchHistory: {claude, sessionId, timestamp, promptCount}
5. Destroy current AgentInstance (kill subprocess)
6. Context plugin builds full history (with/without agent labels per setting)
7. AgentManager.spawn("gemini", workingDir)
8. Session.setContext(history) — inject into new agent
9. Rewire SessionBridge: disconnect old → connect new
10. Session.activate()
11. Update SessionRecord: agentName="gemini", agentSessionId=new
12. Reset promptCount = 0
13. Middleware: agent:afterSwitch
14. Adapter sends: "Switched to gemini (new session)"
```
### Switch back with resume: Gemini → Claude
```
1. Find last entry for "claude" in switchHistory
2. Check: entry.promptCount === 0 AND claude supports resume?
3. YES → AgentManager.resume("claude", workingDir, entry.agentSessionId)
- No history injection needed (agent already has context)
4. Adapter sends: "Switched to claude (resumed)"
```
### Switch back without resume: Gemini → Claude
```
1. Find last entry for "claude" in switchHistory
2. Check: entry.promptCount > 0 OR claude doesn't support resume
3. → AgentManager.spawn("claude", workingDir)
4. → Inject full history
5. Adapter sends: "Switched to claude (new session)"
```
## Session & Bridge Rewiring
### Session.switchAgent()
```typescript
async switchAgent(agentName: string): Promise<void> {
// 1. Save current agent state to switchHistory
this.addSwitchEntry(this.agentName, this.agentSessionId, this.promptCount);
// 2. Disconnect bridge from old agent
this.bridge.disconnect();
// 3. Destroy old agent
await this.agentInstance.destroy();
// 4. Determine: resume or new session?
const lastEntry = this.findLastEntry(agentName);
const resume = lastEntry
&& lastEntry.promptCount === 0
&& agentSupportsResume(agentName);
// 5. Spawn or resume new agent
if (resume) {
this.agentInstance = await AgentManager.resume(
agentName, this.workingDir, lastEntry.agentSessionId
);
} else {
this.agentInstance = await AgentManager.spawn(agentName, this.workingDir);
const history = await contextPlugin.buildHistory(this, {
labelAgent: this.labelSetting,
});
this.setContext(history);
}
// 6. Update session fields
this.agentName = agentName;
this.agentSessionId = this.agentInstance.sessionId;
this.promptCount = 0;
// 7. Reconnect bridge
this.bridge.connect(this.agentInstance);
// 8. Persist
await this.store.save(this.toRecord());
}
```
### Bridge disconnect/connect
`SessionBridge` supports reconnection without creating a new bridge instance:
- `disconnect()` — remove all event listeners from old agent instance
- `connect(newAgentInstance)` — wire event listeners to new agent instance
- Session ID, thread, adapter reference remain unchanged
### Rollback on failure
```
If spawn/resume of new agent fails:
→ Re-spawn old agent (using agentSessionId from entry just saved)
→ Remove last entry from switchHistory
→ Reconnect bridge to old agent
→ Notify user: "Failed to switch, rolled back to <oldAgent>"
If rollback also fails:
→ Session transitions to `error` status
→ User must create new session or retry
```
## Command & UX
### `/switch` command
```
/switch → Show menu with available agents
/switch <agentName> → Switch directly to that agent
/switch label on → Enable agent name labels in history
/switch label off → Disable agent name labels in history
```
### Menu (no argument)
Shows all installed agents except the currently active one, one per row:
```
Switch Agent
[claude]
[gemini]
[codex]
```
### User-facing messages
| Situation | Message |
|-----------|---------|
| Switch success (new) | `Switched to gemini (new session)` |
| Switch success (resume) | `Switched to claude (resumed)` |
| Prompt in-flight | `Agent is responding. Cancel and switch?` + [Yes] [No] |
| Agent not installed | `Agent "xyz" is not installed` |
| Already using agent | `Already using claude` |
| Switch failed | `Failed to switch to gemini: <reason>` |
| Rollback after failure | `Rolled back to claude` |
### Label setting
Configurable via:
- `/switch label on/off` (per-session shortcut)
- Global config setting (default for new sessions)
## Middleware Hooks
### agent:beforeSwitch (blocking)
```typescript
interface BeforeSwitchPayload {
session: Session;
fromAgent: string;
toAgent: string;
}
// Plugin returns false or throws → switch is blocked
```
### agent:afterSwitch (fire-and-forget)
```typescript
interface AfterSwitchPayload {
session: Session;
fromAgent: string;
toAgent: string;
resumed: boolean; // true if resumed, false if new session
}
```
## Context History Format
### With agent labels (`labelAgent = true`)
```markdown
[CONVERSATION HISTORY]
## [claude]
**User:** Help me write a sort function
**Assistant:** Here is the implementation...
## [gemini]
**User:** Optimize this
**Assistant:** Optimized version...
[END CONVERSATION HISTORY]
```
### Without agent labels (`labelAgent = false`)
```markdown
[CONVERSATION HISTORY]
**User:** Help me write a sort function
**Assistant:** Here is the implementation...
**User:** Optimize this
**Assistant:** Optimized version...
[END CONVERSATION HISTORY]
```
### Context plugin changes
- `buildHistory()` adds option `labelAgent: boolean`
- Collects history from **all agent sessions** in switchHistory, merged chronologically
- Excludes system messages (context injection, welcome) — only user prompts and agent responses
## Edge Cases
| Case | Handling |
|------|----------|
| Rapid sequential switches (A→B→C) | Each switch goes through full flow; promptCount=0 recorded for each |
| Process restart mid-session | SessionRecord has switchHistory → lazyResume uses current agentName + agentSessionId; promptCount restored from record |
| Agent uninstalled after switch | Switch back → "Agent not installed", user must reinstall |
| Switch history grows long | No hard limit; context plugin may truncate old history based on token budget |
| Rollback also fails | Session → `error` status; user creates new session or retries |
| Adopt session then switch | Works normally — `originalAgentSessionId` preserved, switchHistory tracks separately |
| Switch to same agent | "Already using <agent>" — no-op |
| Session in `error` status | Switch allowed — new agent may resolve the issue |
## Future: Fork Session
The data model supports future fork functionality:
- `agentSwitchHistory` is a complete timeline — exact timestamps, agents, prompt counts
- Fork = create new session, copy switchHistory up to a checkpoint, continue independently
- Future field: `forkedFrom: { sessionId: string, switchIndex: number }` — points to source session and position in history
Fork is **not** implemented in this spec. The data model is designed to not block it.

View File

@ -1,381 +0,0 @@
# Multi-Instance Support Design
**Date:** 2026-03-30
**Branch:** `feat/multi-instance`
**Approach:** Instance Context Object (Approach B)
## Problem
OpenACP currently supports only one instance per machine. All config, data, sessions, and runtime state are hardcoded to `~/.openacp/`. Users who want to run multiple instances with different configurations (different bots, different agents, different channels) cannot do so.
## Goals
- Run multiple independent OpenACP instances on the same machine simultaneously
- Each instance has its own config, sessions, agents, plugins, ports, and lifecycle
- Auto-detect local instances, support explicit flags for control
- Optionally clone settings from global instance when creating a new local instance
- Full backward compatibility — existing users see no change
## Non-Goals
- Shared sessions or real-time sync between instances
- GUI for managing multiple instances
- Remote instance management
---
## Design
### 1. InstanceContext
A single object that holds all resolved paths for an instance. Created once at CLI entry, passed down through the constructor chain.
```typescript
interface InstanceContext {
/** Unique slug ID (e.g. "main", "my-project", "staging-bot") — from registry */
id: string
/** Instance root directory (e.g. ~/.openacp or /project/.openacp) */
root: string
/** Whether this is the global instance */
isGlobal: boolean
/** All resolved paths — derived from root */
paths: {
config: string // root/config.json
sessions: string // root/sessions.json
agents: string // root/agents.json
registryCache: string // root/registry-cache.json
plugins: string // root/plugins/
pluginsData: string // root/plugins/data/
pluginRegistry: string // root/plugins.json
logs: string // root/logs/
pid: string // root/openacp.pid
running: string // root/running
apiPort: string // root/api.port
apiSecret: string // root/api-secret
bin: string // root/bin/
cache: string // root/cache/
tunnels: string // root/tunnels.json
agentsDir: string // root/agents/ (binary agent installs)
}
}
```
#### Instance Naming
Each instance has a **name** (stored in its own `config.json` as `instanceName`) and a unique **id** (stored in the central registry):
- **name**: Human-readable, provided by user during setup, stored in instance's `config.json`. Default: `"Main"` for global, `"openacp-<N>"` for local. Can be changed later via `openacp config`.
- **id**: Auto-generated slug from name at creation time. Lowercase, hyphens, no spaces. E.g. `"My Staging Bot"` → `"my-staging-bot"`. Must be unique across all instances — if collision, append `-2`, `-3`, etc. ID is immutable after creation.
- Global instance always has id `"main"`.
Used for: lookup (`openacp status --id my-staging-bot`), display, and keying in the registry.
#### Path Resolution (CLI entry, runs once)
User-facing flags always take a **directory path** (not the `.openacp` subfolder). The system appends `/.openacp` internally.
Priority order:
1. `--dir <path>` flag → `<path>/.openacp`
2. `--local` flag → `cwd/.openacp`
3. `--global` flag → `~/.openacp`
4. cwd contains `.openacp/` directory → `cwd/.openacp` (auto-detect, no prompt)
5. No flag, no local dir, global exists → prompt user: "Use your main setup or create a new one here?"
6. Nothing exists → full setup wizard at `~/.openacp` (same as current behavior)
#### Propagation
```
CLI entry (resolveInstanceRoot)
→ startServer(ctx)
→ ConfigManager(ctx)
→ OpenACPCore(ctx)
→ SessionStore(ctx.paths.sessions)
→ AgentStore(ctx.paths.agents)
→ LifecycleManager(ctx)
→ PluginContext (storagePath = ctx.paths.pluginsData/<name>/)
```
Plugins receive their scoped storage path through `PluginContext` (existing pattern). Only the root changes — plugin code does not need to know about multi-instance.
### 2. Instance Registry
A central registry at `~/.openacp/instances.json` (always in global dir) that tracks all known instances for `openacp status --all`.
```typescript
interface InstanceRegistry {
version: 1
instances: Record<string, InstanceRegistryEntry> // key = id (slug)
}
// Minimal — just enough to locate the instance. All details read from the instance's own config/state.
interface InstanceRegistryEntry {
id: string // unique slug (e.g. "main", "my-staging-bot")
root: string // full path to .openacp dir
}
```
The registry is intentionally minimal — it's just an index of known instances. All instance details (name, ports, channels, mode, PID, etc.) are read from the instance's own files:
- **Name:** `<root>/config.json` → `instanceName` field
- **PID:** `<root>/openacp.pid`
- **API port:** `<root>/api.port`
- **Tunnel port:** `<root>/tunnels.json`
- **Run mode:** `<root>/config.json` → `runMode` field
- **Channels:** `<root>/plugins.json` → check which adapter plugins are enabled
This avoids stale data — `openacp status --all` reads live state from each instance directory.
#### Lifecycle
- **On create:** Add entry to registry with `id` + `root`.
- **On start:** Write PID to `<root>/openacp.pid`, write ports to `<root>/api.port` etc. Registry unchanged.
- **On stop:** Remove PID file. Registry unchanged.
- **On status --all:** Read registry for list of instances, then read each instance's own files (PID, config, ports) for live details. Skip entries whose `root` directory no longer exists.
- **On delete:** Remove entry from registry + optionally remove the `.openacp/` directory.
#### Singleton Check Change
Current: Check PID at `~/.openacp/openacp.pid` → blocks ALL instances.
New: Check PID at `<root>/openacp.pid` → only blocks duplicate of same instance. Different roots run concurrently.
### 3. Port Auto-Detection
When running multiple instances, ports will conflict if both use defaults.
- **API server:** Default 21420. If occupied, try +1 up to 10 retries. Write actual port to `<root>/api.port`.
- **Tunnel:** Already has retry logic (tries port+1 up to 10 times). Change path to `<root>/tunnels.json`.
- **User-pinned port:** If user sets a specific port in config, use that exact port. Fail with clear error if occupied (no auto-increment).
### 4. Local Instance Creation & Clone-once Inheritance
#### Creation Flow
```
openacp --local (or user picks "new setup here" from prompt)
→ cwd/.openacp/ does not exist
→ Ask instance name: "Give this setup a name" (default: openacp-<N>)
→ Check if any existing setup is available to copy from
→ One or more exist:
→ "Use settings from an existing setup as a starting point?"
→ Yes: pick which setup (see below)
→ copy with progress → run setup for remaining fields
→ No: run full setup from scratch
→ None exist: run full setup from scratch
```
#### Choosing Which Setup to Copy From
User can copy from **any existing instance**, not just the main one. Two ways:
**Interactive (no flag):**
```
? Use settings from an existing setup as a starting point? (Y/n) Y
? Which setup to copy from?
● Main (/Users/lucas/.openacp)
My Project (/Users/lucas/my-project/.openacp)
Staging Bot (/Users/lucas/staging/.openacp)
```
Each option shows the instance name and full path.
**CLI flag:** `--from <path>` to skip the prompt (path is the parent directory, not `.openacp`):
```
openacp --local --from ~
openacp --local --from ~/other-project
openacp --dir /new/path --from ~/existing
```
Validation: `--from` path must contain a `.openacp/` subdirectory with a `config.json` inside. Error with clear message if not found:
```
Error: No OpenACP setup found at /Users/lucas/other-project/.openacp
```
The list of available setups comes from the Instance Registry (`~/.openacp/instances.json`). If a registered instance's directory no longer exists, it is skipped.
#### Copy Progress
Copying plugins and agents can take time (node_modules can be large). Show step-by-step progress:
```
Copying from "Main" (/Users/lucas/.openacp)...
✓ Configuration
✓ Plugin list
◐ Plugins (47 MB)...
✓ Plugins
✓ Agents
✓ Tools (cloudflared, ...)
✓ Preferences
Done! Copied 52 MB in 3s.
```
Use a spinner for in-progress items and checkmarks for completed ones. Show size for large directories.
#### Plugin Inheritance Declaration
Each plugin declares which settings keys are safe to copy:
```typescript
interface PluginDefinition {
// ... existing fields
inheritableKeys?: string[]
}
```
Examples:
| Plugin | Inheritable | Not Inheritable (needs per-instance setup) |
|--------|-------------|-------------------------------------------|
| Telegram | — | `botToken`, `chatId` (each instance needs its own bot) |
| Discord | — | `botToken`, `guildId` |
| Slack | — | `botToken`, `appToken`, `signingSecret` |
| Tunnel | `provider`, `maxUserTunnels`, `auth` | `port` (would conflict) |
| API server | `host` | `port` (would conflict) |
| Security | `allowedUsers`, `maxSessionsPerUser`, `rateLimits` | — |
| Usage | `budget` | — |
| Speech | `stt.provider`, `tts` | API keys |
#### Clone Process
1. Copy `config.json` from source → target (reset port fields to defaults for auto-detect)
2. Copy `plugins.json` (registry — knows which plugins are enabled)
3. Copy `plugins/package.json` and `plugins/node_modules/` (installed community plugins — avoids re-downloading)
4. Copy `agents.json` and `agents/` directory (installed agent definitions + binaries)
5. Copy `bin/` directory (installed binaries like cloudflared — avoids re-downloading)
6. For each enabled plugin with `inheritableKeys`:
- Read source `plugins/data/<name>/settings.json`
- Keep only inheritable keys
- Write to target `plugins/data/<name>/settings.json`
7. Run setup wizard for missing required fields (bot tokens, etc.)
- Wizard detects partial setup → only asks for fields not yet configured
#### Never Cloned
Sessions, logs, cache, PID file, tunnel registry, api.port, api-secret — each instance starts clean with its own runtime state.
### 5. CLI Changes
#### New Flags
```
openacp [command] [--local | --global | --dir <path>] [--from <path>] [--name <name>]
```
- `--local` — use/create `.openacp/` in current directory
- `--global` — always use `~/.openacp/`
- `--dir <path>` — use/create `.openacp/` at specified directory (system appends `/.openacp` internally)
- `--from <path>` — when creating a new setup, copy settings from this directory's existing setup
- `--name <name>` — set the instance name (only during creation, default: `openacp-<N>`)
All flags except `--from` and `--name` apply to ALL commands. `--from` and `--name` only apply during instance creation.
#### New Subcommand
```
openacp status --all # show all known instances
```
Output:
```
Status ID Name Directory Mode Channels API Tunnel
● online main Main ~ daemon telegram 21420 3100
● online my-project My Project ~/my-project fg discord 21421 3101
○ offline staging-bot Staging Bot ~/staging — telegram — —
```
- **Directory** column shows the parent directory (without `/.openacp` suffix) for readability
- **API** and **Tunnel** show the actual port numbers (or `—` if offline)
- **Mode** shows `daemon`, `fg` (foreground), or `—` if not running
Individual instance by ID: `openacp status --id my-project`
#### Auto-detect Logic (no prompt needed)
1. `.openacp/` exists in cwd → use it
2. Any explicit flag → follow it
3. No local dir + no flag + global exists → prompt (shows name + full path):
```
? How would you like to run OpenACP?
● Use "Main" (/Users/you/.openacp)
Create a new setup here (/Users/you/current-dir)
```
4. Nothing exists → full setup wizard (current behavior)
#### User-Facing Language
All prompts use plain language, always show full paths so user knows exactly where things are:
| Internal concept | User-facing text |
|-----------------|-----------------|
| Global instance | `"Main" (/Users/you/.openacp)` — name + path |
| Local instance | `"My Project" (/Users/you/my-project/.openacp)` — name + path |
| Copy from existing | "Use settings from an existing setup as a starting point" |
| Instance root | "location" with full path shown |
| Auto-detect | (no message, just works) |
| CLI shortcut | Show equivalent command, e.g. "Tip: next time use `openacp --local`" |
| Instance name prompt | "Give this setup a name" (default shown) |
### 6. Files to Modify
#### Core (receive `InstanceContext` via constructor)
- `ConfigManager` — receive `ctx.paths.config` instead of hardcoded path
- `OpenACPCore` — receive ctx, pass to session store, command registry
- `LifecycleManager` — receive ctx, use `ctx.paths.pluginsData` for plugin storage
- `SessionStore` — receive `ctx.paths.sessions`
- `AgentStore` — receive `ctx.paths.agents`
- `AgentCatalog` — receive `ctx.paths.registryCache`
- `AgentInstaller` — receive `ctx.paths.agentsDir` for binary agent installs
- `SettingsManager` — receive `ctx.paths.pluginsData` as base
- `PluginRegistry` — receive `ctx.paths.pluginRegistry`
#### CLI Commands (receive ctx from resolution)
- `daemon.ts` — PID path, log dir, running marker from ctx
- `default.ts` — use ctx instead of module-level consts
- `api-client.ts` — port file, secret file from ctx
- `plugins.ts` — registry path, plugins dir from ctx
- `install.ts` / `uninstall.ts` — plugins dir from ctx
- `reset.ts` — root dir from ctx
- `start.ts` / `stop.ts` / `status.ts` — ctx-aware
- `autostart.ts` — launchd/systemd paths (global only)
#### Plugins (minimal — most already use PluginContext.storage)
- `api-server` — port file and secret file path from ctx instead of hardcode
- `tunnel-registry` — registry path from ctx instead of module-level const
- `context-manager` — cache path from ctx
- `file-service` — base path from ctx
- `install-binary` — bin dir from ctx
#### No Changes Needed
- Plugin business logic (telegram, discord, slack, speech, security, usage, notifications)
- Agent subprocess spawning
- Middleware chain, event bus, service registry
### 7. New Code
1. `InstanceContext` type (with `id`) + `resolveInstanceRoot()` + `createInstanceContext()` factory
2. `InstanceRegistry` class (minimal index: id + root path, read/write `~/.openacp/instances.json`)
3. Instance naming: `instanceName` field in config schema, slug generation for id, uniqueness check
4. Copy logic in setup wizard (partial setup detection + inheritance + progress display)
5. `inheritableKeys` field in plugin definition type
6. API server port auto-detect (tunnel already has this)
7. `--local`, `--global`, `--dir`, `--from`, `--name` flag parsing in CLI entry
8. `status --all` and `status --id <id>` subcommands
9. User-facing prompt when no flag and cwd has no `.openacp/` (with names + full paths)
10. Setup copy selection UI (list existing instances from registry, validate `--from` path)
### 8. Backward Compatibility
| Scenario | Before | After |
|----------|--------|-------|
| `openacp` with existing `~/.openacp/` | Starts global | Same — starts global |
| `~/.openacp/config.json` from old version | Loads fine | Loads fine, no migration needed |
| Daemon running, upgrade version | PID check at `~/.openacp/openacp.pid` | Same path, same check |
| `OPENACP_CONFIG_PATH` env var | Overrides config path | Still works, overrides `ctx.paths.config` |
| All `OPENACP_*` env vars | Override config values | Still work as before |
| No `.openacp/` in cwd, no flags | Goes to global | Same — goes to global (with prompt if global exists) |
The `instances.json` file is new and additive — old versions simply won't have it.

View File

@ -1,202 +0,0 @@
# Spec 1: API Server Core (Fastify Refactor)
**Date:** 2026-03-31
**Status:** Draft
**Related specs:**
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
- [Spec 3: SSE Adapter](./2026-03-31-sse-adapter-design.md)
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
## Overview
Refactor the existing API server plugin (`@openacp/api-server`) from Node.js native `http` module to **Fastify**. The current implementation uses a custom regex-based router, inline auth, and manual JSON parsing. The new implementation provides structured routing, schema validation, proper error handling, and plugin extensibility for third-party route registration.
## Decision: Why Fastify
Evaluated NestJS vs Fastify. Chose Fastify because:
- **Lightweight** (~2MB vs ~15-20MB for NestJS) — important for CLI tool
- **No lifecycle conflict** — Fastify doesn't fight OpenACP's existing LifecycleManager
- **ESM first-class** — matches codebase (ESM-only, NodeNext resolution)
- **Plugin architecture** aligns with OpenACP plugin system
- **Hooks system** maps to existing middleware chain pattern
- **Zod integration** via `fastify-type-provider-zod` for schema validation
## Plugin Structure
```
src/plugins/api-server/
index.ts — Plugin definition, setup/teardown
server.ts — Fastify instance creation, global hooks, error handler
service.ts — ApiServerService implementation (expose for plugins)
routes/
sessions.ts — /api/v1/sessions/*
agents.ts — /api/v1/agents/*
config.ts — /api/v1/config/*
system.ts — /api/v1/system/* (health, version, restart)
commands.ts — /api/v1/commands/*
auth.ts — /api/v1/auth/* (cross-ref Spec 2)
middleware/
auth.ts — Auth preHandler (cross-ref Spec 2)
error-handler.ts — Global error handler
schemas/ — Zod schemas for request/response validation
static-server.ts — Preserved, serves UI dashboard
```
## Fastify Instance Setup
```typescript
// server.ts
const app = Fastify({ logger: false }); // use OpenACP logger instead of pino
// Plugins
app.register(cors, { origin: true });
app.register(fastifySwagger, { openapi: { info: { title: 'OpenACP API', version: '1.0.0' } } });
app.register(fastifySwaggerUi, { routePrefix: '/api/docs' });
app.register(fastifyZod); // Zod type provider
app.register(fastifyRateLimit, { max: 100, timeWindow: '1 minute' });
// Global error handler
app.setErrorHandler(globalErrorHandler);
// Route plugins
app.register(sessionRoutes, { prefix: '/api/v1/sessions' });
app.register(agentRoutes, { prefix: '/api/v1/agents' });
app.register(configRoutes, { prefix: '/api/v1/config' });
app.register(systemRoutes, { prefix: '/api/v1/system' });
app.register(commandRoutes, { prefix: '/api/v1/commands' });
app.register(authRoutes, { prefix: '/api/v1/auth' });
```
## API Versioning
All routes prefixed with `/api/v1/`. This allows adding `/api/v2/` in the future without breaking existing clients.
Plugin-registered routes use `/api/plugins/<plugin-name>/*` prefix.
## Error Handling
Consistent error format across all routes:
```typescript
interface ApiError {
error: {
code: string; // e.g. "SESSION_NOT_FOUND", "VALIDATION_ERROR"
message: string;
statusCode: number;
details?: unknown; // validation errors, etc.
}
}
```
Global error handler maps:
- `ZodError` → 400 `VALIDATION_ERROR`
- `NotFoundError` → 404
- `AuthError` → 401/403
- Unknown errors → 500 `INTERNAL_ERROR`
## Service Interface (Plugin Extensibility)
API server exposes a service for other plugins to register their own routes:
```typescript
interface ApiServerService {
// Plugin route registration — hybrid Fastify plugin pattern
registerPlugin(prefix: string, plugin: FastifyPluginAsync, opts?: {
auth?: boolean; // default true — auto-apply auth preHandler
}): void;
// Auth helpers for plugin reuse (cross-ref Spec 2)
authPreHandler: preHandlerHookHandler;
requireScopes(...scopes: string[]): preHandlerHookHandler;
requireRole(role: string): preHandlerHookHandler;
// Metadata
getPort(): number;
getBaseUrl(): string; // localhost URL
getTunnelUrl(): string | null; // tunnel URL if available
}
```
**How plugins register routes:**
```typescript
// Example: usage plugin adding API routes
setup(ctx) {
const api = ctx.getService<ApiServerService>('api-server');
api.registerPlugin('/api/plugins/usage', async (app) => {
// Auth helpers from API server — reusable, less code
app.addHook('onRequest', api.authPreHandler);
app.get('/stats', { preHandler: api.requireScopes('usage:read') }, getStats);
app.post('/reset', { preHandler: api.requireRole('admin') }, resetStats);
});
}
```
When a plugin teardowns, its registered routes are automatically unregistered.
## Route Details (V1)
### Sessions (`/api/v1/sessions`)
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/` | List sessions (filter: status, agentName) | `sessions:read` |
| `GET` | `/:id` | Session detail (metadata, status, prompt count) | `sessions:read` |
| `POST` | `/` | Create session (agentName, workingDirectory?) | `sessions:write` |
| `DELETE` | `/:id` | Cancel session | `sessions:write` |
| `POST` | `/:id/prompt` | Enqueue prompt | `sessions:prompt` |
| `POST` | `/:id/permission` | Resolve permission request | `sessions:permission` |
| `PATCH` | `/:id` | Update session (switch agent, toggle voice/dangerous mode) | `sessions:write` |
### Agents (`/api/v1/agents`)
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/` | List agent catalog with capabilities | `agents:read` |
| `GET` | `/:name` | Agent detail | `agents:read` |
### Config (`/api/v1/config`)
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/` | Full config (safe fields only, unless admin) | `config:read` |
| `PATCH` | `/` | Update config fields | `config:write` |
| `GET` | `/schema` | Zod schema as JSON Schema (for app UI form generation) | `config:read` |
### System (`/api/v1/system`)
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/health` | Health + memory + uptime + adapters (unauthenticated OK) | — |
| `GET` | `/version` | Version info | `system:health` |
| `POST` | `/restart` | Graceful restart | `system:admin` |
### Commands (`/api/v1/commands`)
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/` | List all registered commands | `commands:execute` |
| `POST` | `/execute` | Execute command `{ command: "/help", sessionId?: "..." }` | `commands:execute` |
### Auth (`/api/v1/auth`) — see Spec 2
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `POST` | `/tokens` | Generate JWT (secret token only) | `auth:manage` |
| `GET` | `/tokens` | List active tokens | `auth:manage` |
| `DELETE` | `/tokens/:id` | Revoke token | `auth:manage` |
| `POST` | `/refresh` | Refresh JWT | — (valid JWT) |
| `GET` | `/me` | Current token info | — (valid JWT) |
## Dependencies
New npm packages:
- `fastify`
- `@fastify/cors`
- `@fastify/swagger`
- `@fastify/swagger-ui`
- `@fastify/rate-limit`
- `fastify-type-provider-zod`
## Migration
- Existing API server functionality preserved — all current endpoints migrated to new route structure under `/api/v1/`
- Static server (UI dashboard) preserved as-is
- `api.port` and `api-secret` file management preserved
- Backward-compatible: old clients hitting `/api/*` without `v1` prefix should get 301 redirect to `/api/v1/*` (migration period)

View File

@ -1,243 +0,0 @@
# Spec 4: App Connectivity
**Date:** 2026-03-31
**Status:** Draft
**Related specs:**
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
- [Spec 3: SSE Adapter](./2026-03-31-sse-adapter-design.md)
## Overview
Mechanisms for app clients (desktop/web) to discover and connect to OpenACP instances — both locally (same machine) and remotely (via tunnel). Includes the `openacp remote` CLI command for generating access links with tokens.
## CLI Command: `openacp remote`
### Usage
```
openacp remote [flags]
--role <role> Role for token (default: admin)
--expire <duration> JWT expiry (default: 24h, e.g.: 1h, 7d, 30d)
--scopes <scopes> Override scopes (comma-separated)
--name <label> Token label (default: auto-generated)
--no-tunnel Localhost only, don't auto-start tunnel
--no-qr Don't show QR code
--instance <id> Specific instance (multi-instance support)
```
### Auto-generated Name Format
Pattern: `remote-HHhMM-DD-MM-YYYY`
Example: `remote-14h30-31-03-2026`
### Command Flow
```
openacp remote
→ Load instance config (respect --instance flag)
→ Check API server running?
→ Read <instanceRoot>/api.port
→ File missing → error: "API server not running, start with: openacp start"
→ File exists → GET http://localhost:<port>/api/v1/system/health → confirm alive
→ Read secret token from <instanceRoot>/api-secret
→ POST http://localhost:<port>/api/v1/auth/tokens
→ Authorization: Bearer <secret-token>
→ Body: { role: "admin", expire: "24h", name: "remote-14h30-31-03-2026" }
→ Receive JWT access token + metadata
→ Tunnel handling:
→ --no-tunnel flag: skip tunnel
→ Tunnel already running: get tunnel URL from tunnel plugin service
→ Tunnel not running: auto-start tunnel
→ Read tunnel config from instance config
→ Config exists: start with configured provider
→ No config: prompt user to choose provider
→ cloudflare (no account needed, recommended)
→ ngrok (needs auth token)
→ bore (self-hosted)
→ tailscale (private network)
→ Start tunnel → wait for URL
→ Generate 3 link formats
→ Display output
```
### Output Format
```
╔══════════════════════════════════════════════════════════════╗
║ OpenACP Remote Access ║
╠══════════════════════════════════════════════════════════════╣
║ ║
║ Token: remote-14h30-31-03-2026 ║
║ Role: admin ║
║ Expires: 2026-04-01 14:30 (24h) ║
║ Refresh: until 2026-04-07 14:30 (7d) ║
║ ║
║ Local: ║
║ http://localhost:3100?token=eyJ... ║
║ ║
║ Tunnel: ║
║ https://abc-123.trycloudflare.com?token=eyJ... ║
║ ║
║ App: ║
║ openacp://connect?host=abc-123.trycloudflare.com&token=eyJ ║
║ ║
║ ██████████████████████ ║
║ ██ QR (tunnel link) ██ ║
║ ██████████████████████ ║
║ ║
╚══════════════════════════════════════════════════════════════╝
```
QR code encodes the tunnel link (preferred) or localhost link if `--no-tunnel`. Rendered as ASCII art in terminal using a lightweight package like `qrcode-terminal`.
## App Discovery (Localhost)
When the app runs on the same machine, it can auto-discover running OpenACP instances.
### Mechanism
The app reads the global instance registry at `~/.openacp/instances.json` which contains all registered instances and their root paths.
```json
{
"version": 1,
"instances": {
"main": { "id": "main", "root": "/Users/user/.openacp" },
"dev": { "id": "dev", "root": "/path/to/project/.openacp" }
}
}
```
### Discovery Flow
```
App start (local mode)
→ Read ~/.openacp/instances.json
→ For each instance in registry:
→ Read <root>/api.port → file exists? Instance potentially running
→ GET http://localhost:<port>/api/v1/system/health → confirm alive
→ Read <root>/config.json → get instanceName
→ Filter: only keep instances that are running (api.port exists + health OK)
→ 0 running: show "Paste link or scan QR" input
→ 1 running: auto-connect to that instance
→ N running: show list for user to choose
→ Display: instanceName, instanceId, port
→ After selection:
→ Read <root>/api-secret → auto-auth with secret token
→ Connected, full access
```
### Local Auto-Auth
The app reads `<instanceRoot>/api-secret` directly from the file system (same machine, same user — file permission `0o600`). This provides zero-friction authentication for local connections without requiring token paste or QR scan.
## App Connection Flows
### Case 1: Local (Auto-Discover)
```
App start
→ Discovery flow (see above)
→ Found running instance(s)
→ Select instance (auto if single)
→ Read <root>/api-secret from filesystem
→ Use secret token for API auth (full access)
→ Connect SSE stream for sessions
→ Ready
```
No token paste required. Seamless local experience.
### Case 2: Remote (Paste Link / QR Scan)
```
User pastes link or scans QR code
→ App parses URL → extract host + token
→ GET {host}/api/v1/auth/me
→ 200: token valid → proceed
→ Response includes role, scopes, expiresAt
→ 401/403: token invalid/expired → show error + prompt re-enter
→ Network error: host unreachable → show error
→ Token valid → store securely (OS keychain / credential store)
→ Clear token from URL/browser history
→ Use Authorization header for all subsequent requests
→ Connect SSE stream
→ Ready
```
### Case 3: Custom Scheme (Desktop App)
```
User clicks: openacp://connect?host=abc-123.trycloudflare.com&token=eyJ...
→ OS opens desktop app with URL params
→ App parses: extract host + token
→ GET {host}/api/v1/auth/me → verify token (same as Case 2)
→ Fail: show error with details
→ OK: store token, connect
→ Ready
```
## Tunnel Auto-Start
When `openacp remote` runs and no tunnel is active:
```
→ Get tunnel plugin service: ctx.getService('tunnel')
→ Plugin not installed?
→ Error: "Tunnel plugin not installed. Install with: openacp plugin install @openacp/tunnel"
→ Plugin installed, check tunnel status
→ Tunnel already running → return existing URL
→ Tunnel not running:
→ Read tunnel config from instance config
→ Config exists (provider selected) → start tunnel with config
→ No config → prompt user to choose provider:
→ cloudflare (recommended, no account needed)
→ ngrok (needs auth token)
→ bore (self-hosted)
→ tailscale (private network)
→ Save chosen provider to config
→ Start tunnel → wait for URL → return URL
```
## Link Formats
Three formats generated for different connection scenarios:
### 1. HTTP Local Link
```
http://localhost:<port>?token=<jwt>
```
For: Browser on same machine, or app fallback when auto-discover unavailable.
### 2. HTTP Tunnel Link
```
https://<tunnel-subdomain>.<provider-domain>?token=<jwt>
```
For: Remote browser access, mobile browser, sharing with others.
### 3. Custom Scheme Link
```
openacp://connect?host=<tunnel-host>&token=<jwt>&port=<port>
```
For: Desktop app deep linking. OS routes to installed OpenACP app. Includes both tunnel host and local port for flexibility.
## Security Considerations
- **Token in URL**: JWT in query params risks being logged by proxies/servers. Mitigations:
- Short-lived tokens (default 24h)
- Revokable via token management API
- App should swap to header-based auth immediately after initial connect
- App should clear token from URL/history after parsing
- **Local file access**: `api-secret` readable only by same OS user (file permission `0o600`). Never exposed via API.
- **Tunnel exposure**: All API routes require authentication when accessed via tunnel. The only exception is `GET /api/v1/system/health` which returns minimal info (`{ status: "ok" }`) without sensitive data — needed for app discovery verification.
- **Token swap flow** (recommended for apps):
1. Parse token from URL
2. Call `GET /api/v1/auth/me` to verify token and get metadata
3. Store token in secure storage (OS keychain, credential store)
4. Clear token from URL, query params, browser history
5. Use `Authorization: Bearer <token>` header for all subsequent requests
## New Dependencies
- `qrcode-terminal` — ASCII QR code rendering in terminal (for `openacp remote` output)

View File

@ -1,234 +0,0 @@
# Spec 2: Auth System
**Date:** 2026-03-31
**Status:** Draft
**Related specs:**
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
- [Spec 3: SSE Adapter](./2026-03-31-sse-adapter-design.md)
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
## Overview
Two-tier authentication system for the API server: **Secret Token** (master key, local) and **JWT Access Token** (generated, scoped, revokable, stateful). Supports role-based access with optional scope overrides.
## Secret Token
Existing mechanism preserved — random 64-character hex string stored in `<instanceRoot>/api-secret` with file permission `0o600`.
**Behavior:**
- Request with `Authorization: Bearer <secret-token>` → timing-safe compare → **full access** to all endpoints
- Bypasses JWT entirely — no expiry, no scopes, no roles
- Cannot be revoked (regenerate by deleting file + restart)
- Used by: local CLI tools, local app auto-auth, `openacp remote` to generate JWTs
## JWT Flow
### Generate Token
Only callable with secret token auth:
```
POST /api/v1/auth/tokens
Authorization: Bearer <secret-token>
Body: {
"role": "admin",
"name": "remote-14h30-31-03-2026",
"expire": "24h",
"scopes": ["sessions:read", "sessions:prompt"] // optional override
}
Response: {
"accessToken": "eyJ...",
"tokenId": "tok_abc123",
"expiresAt": "2026-04-01T14:30:00Z",
"refreshDeadline": "2026-04-07T14:30:00Z"
}
```
### Refresh Token
Use current (potentially expired) JWT to get a new one — as long as refresh deadline hasn't passed:
```
POST /api/v1/auth/refresh
Authorization: Bearer <current-jwt>
Response: {
"accessToken": "eyJ...", // new JWT, expires in 24h
"tokenId": "tok_abc123", // same tokenId
"expiresAt": "2026-04-02T...",
"refreshDeadline": "2026-04-07T..." // unchanged, 7 days from original creation
}
```
**Refresh rules:**
- JWT expired but `refreshDeadline` not passed → new JWT issued
- `refreshDeadline` passed (>7 days from original token creation) → 401, must generate new token with secret token
- Token revoked → 401, cannot refresh
**Important:** The refresh endpoint verifies JWT signature only — it skips the `exp` check. This allows expired JWTs (within refresh deadline) to obtain a new token. All other endpoints reject expired JWTs normally.
### JWT Payload
```typescript
interface JwtPayload {
sub: string; // tokenId (tok_abc123)
role: string; // admin | operator | viewer
scopes?: string[]; // override scopes (null = use role defaults)
iat: number; // issued at
exp: number; // expires at
rfd: number; // refresh deadline timestamp
}
```
### Signing
HMAC-SHA256. Signing key derived from a separate JWT secret stored at `<instanceRoot>/jwt-secret` (auto-generated on first use, similar to `api-secret`). Separate from `api-secret` so rotating one doesn't invalidate the other.
## Roles & Scopes
### Built-in Roles (V1)
3 hardcoded roles. Custom roles planned for V2.
| Role | Scopes |
|---|---|
| `admin` | `*` (all scopes) |
| `operator` | `sessions:read`, `sessions:write`, `sessions:prompt`, `sessions:permission`, `agents:read`, `commands:execute`, `system:health` |
| `viewer` | `sessions:read`, `agents:read`, `system:health` |
### Scope List (V1)
| Scope | Description |
|---|---|
| `sessions:read` | List and get session details |
| `sessions:write` | Create, cancel, update sessions |
| `sessions:prompt` | Enqueue prompts to sessions |
| `sessions:permission` | Resolve permission requests |
| `agents:read` | List and get agent details |
| `config:read` | Read config |
| `config:write` | Update config fields |
| `commands:execute` | Execute chat commands |
| `system:health` | Health check, version info |
| `system:admin` | Restart, system management |
| `auth:manage` | Create/revoke/list tokens |
### Scope Override
When a token has explicit `scopes` array → only those scopes apply, role defaults ignored. This allows creating narrow tokens (e.g., `viewer` role but with only `sessions:read` scope).
## Token Storage (Stateful)
### Data Model
```typescript
interface StoredToken {
id: string; // tok_<random> (e.g., tok_abc123)
name: string; // "remote-14h30-31-03-2026"
role: string; // admin | operator | viewer
scopes?: string[]; // optional scope override
createdAt: string; // ISO 8601
refreshDeadline: string; // ISO 8601, 7 days from createdAt
lastUsedAt?: string; // ISO 8601, updated on each request
revoked: boolean; // true = all requests rejected
}
```
### Storage Mechanism
File: `<instanceRoot>/tokens.json`
Pattern: In-memory Map for fast lookup + persist to JSON file on every change. Same pattern as `JsonFileSessionStore`.
```typescript
class TokenStore {
private tokens: Map<string, StoredToken>;
private filePath: string;
load(): Promise<void>; // read from disk into memory
save(): Promise<void>; // persist memory to disk
create(opts: CreateTokenOpts): StoredToken;
get(id: string): StoredToken | undefined;
revoke(id: string): void;
list(): StoredToken[];
updateLastUsed(id: string): void;
cleanup(): void; // remove expired tokens (refreshDeadline passed)
}
```
### Token Management Endpoints
| Method | Path | Description | Auth Required |
|--------|------|-------------|---------------|
| `POST` | `/api/v1/auth/tokens` | Generate new JWT | Secret token only |
| `GET` | `/api/v1/auth/tokens` | List active tokens | `auth:manage` |
| `DELETE` | `/api/v1/auth/tokens/:id` | Revoke token | `auth:manage` |
| `POST` | `/api/v1/auth/refresh` | Refresh JWT | Valid JWT (even expired, within refresh deadline) |
| `GET` | `/api/v1/auth/me` | Current token info (role, scopes, expiry) | Any valid auth |
## Auth Middleware Flow
```
Request arrives
→ Extract Authorization header (Bearer token)
→ No token? → SSE route? Check ?token= query param
→ No token at all? → 401 Unauthorized
→ Is it the secret token?
→ timing-safe compare against api-secret
→ Match: attach { type: 'secret', role: 'admin', scopes: ['*'] } to request
→ Full access, skip all further checks
→ Is it a JWT?
→ Verify HMAC-SHA256 signature with jwt-secret
→ Invalid signature → 401
→ Decode payload → extract tokenId (sub)
→ Check TokenStore: is tokenId revoked?
→ Yes → 401 "Token revoked"
→ Check exp: is JWT expired?
→ Yes → 401 "Token expired" (client should call /refresh)
→ Attach { type: 'jwt', tokenId, role, scopes } to request
→ Proceed to route handler
→ Route handler uses requireScopes() / requireRole() for fine-grained checks
```
### Fastify Request Decorator
```typescript
declare module 'fastify' {
interface FastifyRequest {
auth: {
type: 'secret' | 'jwt';
tokenId?: string; // undefined for secret token
role: string; // 'admin' for secret token
scopes: string[]; // ['*'] for secret token
}
}
}
```
### Auth Helpers (exposed via ApiServerService)
```typescript
// Pre-handler that verifies auth (secret or JWT)
authPreHandler: preHandlerHookHandler;
// Pre-handler that checks specific scopes
requireScopes(...scopes: string[]): preHandlerHookHandler;
// Logic: if auth.scopes includes '*' → pass. Otherwise check intersection.
// Pre-handler that checks role
requireRole(role: string): preHandlerHookHandler;
// Logic: admin > operator > viewer hierarchy
```
## Security Considerations
- JWT secret separate from API secret — rotating one doesn't affect the other
- Token revocation is immediate (in-memory check before JWT verification)
- `lastUsedAt` tracking helps identify stale tokens
- Automatic cleanup of tokens past their refresh deadline
- Rate limiting on auth endpoints (via Spec 1 Fastify rate limiter)
- Secret token never leaves the local machine file system
- JWT in query params (for SSE) is a known trade-off — mitigated by short expiry + revokability

View File

@ -1,263 +0,0 @@
# Core Module Refactor Design
**Date**: 2026-03-31
**Scope**: `src/core/` — 3-phase incremental refactor
**Goal**: Break up god objects (`core.ts`, `session.ts`), decouple plugin service dependencies from core, improve testability and maintainability.
## Problem Statement
Three structural issues in the core module:
1. **`core.ts` (929 lines)** — God object. Handles message routing, session creation (5 variants), agent switching (200 lines with rollback), lazy resume, bridge management, adapter lifecycle, and config hot-reload.
2. **`session.ts` (569 lines)** — Session class owns TTS/STT logic (~100 lines) that belongs in the speech plugin, not core.
3. **Tight coupling to plugin services** — `OpenACPCore` directly accesses `speechService`, `securityGuard`, `tunnelService` via lazy getters. `MessageTransformer` has direct dependency on `TunnelService` for viewer link generation.
## Approach
**Incremental — 3 phases**, each independently testable and deployable. Each phase is a separate commit/PR scope.
---
## Phase 1: Split `core.ts` (~929 → ~400 lines) + organize loose files
### 1d. Group `instance-*` files into `core/instance/`
Four instance-related files sit loose at the root of `core/`:
- `instance-context.ts` (90 lines) — path definitions, resolve instance root
- `instance-registry.ts` (64 lines) — registry CRUD (JSON file)
- `instance-discovery.ts` (63 lines) — find running instances via health check
- `instance-copy.ts` (112 lines) — clone instance config/plugins/agents
All belong to the same domain: **multi-instance management**. Move into `core/instance/` with an `index.ts` re-exporting public API. Update all import paths. No logic changes.
### 1a. Extract `AgentSwitchHandler`
**New file**: `src/core/agent-switch-handler.ts` (~200 lines)
Extract from `core.ts`:
- `switchSessionAgent()` (lock guard)
- `_doSwitchSessionAgent()` (full switch flow with rollback)
- `switchingLocks` set
**Dependencies injected via constructor**:
```typescript
interface AgentSwitchDeps {
sessionManager: SessionManager;
agentManager: AgentManager;
configManager: ConfigManager;
middlewareChain: MiddlewareChain;
eventBus: EventBus;
adapters: Map<string, IChannelAdapter>;
bridges: Map<string, SessionBridge>;
createBridge: (session: Session, adapter: IChannelAdapter) => SessionBridge;
getService: <T>(name: string) => T | undefined;
}
```
**`OpenACPCore` becomes**:
```typescript
async switchSessionAgent(sessionId: string, toAgent: string) {
return this.agentSwitchHandler.switch(sessionId, toAgent);
}
```
### 1b. Move lazy resume into `SessionFactory`
Move from `core.ts` into `SessionFactory`:
- `lazyResume()` method
- `getOrResumeSession()` method
- `resumeLocks` map
**Rationale**: `lazyResume()` calls `this.createSession()` on Core, which is a full pipeline (spawn agent, create thread, connect bridge, persist). Moving into `SessionManager` would require injecting this entire pipeline as a callback — awkward and creates implicit circular dependency. `SessionFactory` already owns session creation and has `agentManager` + `sessionManager`. It needs one additional callback `onSessionCreated(session, params)` for Core to handle thread creation + bridge wiring + persistence.
**SessionFactory gains**:
```typescript
// Callback for Core to wire thread + bridge + persist after factory creates the session
onSessionCreated?: (session: Session, params: SessionCreateParams & { threadId?: string }) => Promise<void>;
async getOrResume(channelId: string, threadId: string): Promise<Session | null>
private async lazyResume(channelId: string, threadId: string): Promise<Session | null>
```
**SessionFactory needs**: Access to `SessionStore` (for `findByPlatform` lookup) and `adapters` map (for error feedback). These are injected via constructor.
### 1c. Move convenience session creation methods into `SessionFactory`
Move from `core.ts` into `SessionFactory`:
- `handleNewSession()` (~20 lines) — resolves default agent + workspace, calls create
- `handleNewChat()` (~30 lines) — finds current session's agent, creates new session
- `createSessionWithContext()` (~30 lines) — creates session with context injection
**Keep in `core.ts`**:
- `adoptSession()` (~130 lines) — This is an API endpoint handler that does validation (agent caps, cwd exists, session limit check, adapter lookup) before calling `createSession()`. It's orchestration logic, not factory logic.
- `createSession()` — remains as the primary orchestration entry point
### Phase 1 Result
`core.ts` retains:
- Constructor + service getters (~80 lines)
- `registerAdapter()`, `start()`, `stop()` (~50 lines)
- `handleMessage()` — delegates to SessionFactory for lookup/resume (~30 lines)
- `createSession()` — thin orchestration: factory.create() + thread + bridge + persist (~70 lines)
- `adoptSession()` — validation + orchestration (~130 lines)
- `archiveSession()` (~30 lines)
- `createBridge()` (~15 lines)
**Estimated: ~400 lines**
---
## Phase 2: Clean up `session.ts` (569 → ~400 lines)
### 2a. Extract TTS/Voice logic into speech plugin
**Remove from `session.ts`**:
- `TTS_PROMPT_INSTRUCTION` constant
- `TTS_BLOCK_REGEX`, `TTS_MAX_LENGTH`, `TTS_TIMEOUT_MS`
- `maybeTranscribeAudio()` method (~55 lines)
- `processTTSResponse()` method (~40 lines)
- TTS accumulator logic in `processPrompt()` (~20 lines)
**Challenge**: TTS is **stateful across the prompt lifecycle**:
1. Before prompt: check voiceMode, inject `TTS_PROMPT_INSTRUCTION` into prompt text
2. During prompt: accumulate text from `agent_event` emissions
3. After prompt: extract `[TTS]` block from accumulated text, synthesize audio
A single middleware hook cannot handle this because accumulation happens during prompt execution.
**Solution — event-driven approach**:
1. **STT (before prompt)**: Speech plugin registers `agent:beforePrompt` middleware. Middleware checks session voiceMode, transcribes audio attachments, injects `TTS_PROMPT_INSTRUCTION`. Session no longer knows about STT.
2. **TTS (during + after prompt)**: Speech plugin listens on `EventBus` for `turn:start` (already emitted). On `turn:start`, plugin attaches a temporary `agent_event` listener on the session to accumulate text. On `turn:end` (already emitted), plugin detaches listener, extracts `[TTS]` block, synthesizes audio, and emits `audio_content` event back on the session.
The `turn:end` event payload already includes `sessionId`. Speech plugin looks up the session via SessionManager to emit back.
**Session changes**:
- `voiceMode` property stays on Session (it's session state)
- `speechService` property removed from Session constructor and SessionFactory
- `processPrompt()` becomes simpler — no TTS/STT branching, just: context injection → middleware → prompt → emit turn:end
### 2b. Keep auto-name in Session
Auto-name uses `agentInstance.prompt()` + `pause()/resume()` emitter. Tightly coupled to Session internals. Not worth extracting.
### Phase 2 Result
`session.ts` retains:
- State machine (~40 lines)
- PromptQueue + processPrompt (simplified, ~60 lines)
- PermissionGate integration (~10 lines)
- Context injection (~15 lines)
- ACP state management (modes/config/model, ~60 lines)
- Agent switch (in-place, ~50 lines)
- Auto-name (~35 lines)
- destroy/warmup (~40 lines)
**Estimated: ~400 lines**
---
## Phase 3: Decouple plugin services
### 3a. Remove tunnel awareness from `MessageTransformer`
**Current**: `MessageTransformer` has `tunnelService` property and `enrichWithViewerLinks()` (110 lines) that directly calls tunnel service APIs.
**Change**: Extract viewer link enrichment into a post-transform middleware hook.
**New middleware hook**: `message:afterTransform` — fired in `SessionBridge.handleAgentEvent()` after `messageTransformer.transform()` returns.
```typescript
// Hook payload
{
event: AgentEvent;
message: OutgoingMessage;
sessionContext: { id: string; workingDirectory: string };
}
```
**Tunnel plugin** registers middleware on `message:afterTransform` that:
1. Calls `extractFileInfo()` on the event
2. Stores diffs/files via tunnel store
3. Enriches `message.metadata` with `viewerLinks` and `diffStats`
**`MessageTransformer` becomes**: Pure `AgentEvent → OutgoingMessage` mapper. No service dependencies. ~200 lines.
**Note**: `computeLineDiff()` and diff stats computation for rawInput stay in `MessageTransformer` — they're pure transform logic, not tunnel-dependent.
### 3b. Graceful service access in Core
**Current**:
```typescript
private getService<T>(name: string): T {
const svc = this.lifecycleManager.serviceRegistry.get<T>(name);
if (!svc) throw new Error(`Service '${name}' not registered`);
return svc;
}
```
**Change**: Return `undefined` instead of throwing. Core handles missing services gracefully:
```typescript
private getService<T>(name: string): T | undefined {
return this.lifecycleManager.serviceRegistry.get<T>(name);
}
```
**Impact on callers**:
- `securityGuard` — if undefined, **deny all requests** and log error. Security must fail closed, not open. A missing security plugin means misconfiguration, not "allow everyone".
- `notificationManager` — if undefined, skip notifications silently.
- `fileService` — if undefined, skip file operations (images/audio won't be saved).
- `speechService` — if undefined, voice features disabled (already handled).
- `contextManager` — if undefined, skip context injection.
### 3c. Remove `tunnelService` property from Core
**Current**: `OpenACPCore` has `tunnelService` getter/setter that propagates to `MessageTransformer`.
**Change**: Remove `tunnelService` property and `_tunnelService` field from Core. Tunnel plugin registers itself via ServiceRegistry. Tunnel middleware (from 3a) accesses tunnel service via ServiceRegistry directly.
**Impact on `SessionFactory.wireSideEffects()`**: Currently receives `tunnelService` from Core for tunnel cleanup on session end. Change to: tunnel plugin registers `session:afterDestroy` middleware (already supported) to clean up its own tunnels. `wireSideEffects` no longer needs tunnel dependency — remove `tunnelService` from `SideEffectDeps` interface.
### Phase 3 Result
- `MessageTransformer`: pure transform, no service deps (~200 lines)
- `OpenACPCore`: no direct tunnel coupling, graceful service degradation
- `SessionFactory`: no tunnel dependency
- Plugin services fully decoupled — core never throws on missing optional service
---
## New Middleware Hooks
| Hook | Phase | Type | Fired from | Purpose |
|------|-------|------|-----------|---------|
| `message:afterTransform` | 3 | Modifiable | `SessionBridge.handleAgentEvent()` | Enrich outgoing messages post-transform (viewer links, etc.) |
**No new hooks needed for Phase 2** — speech plugin uses existing `agent:beforePrompt` middleware + existing `turn:start`/`turn:end` events on EventBus.
---
## Migration & Backward Compatibility
- **No public API changes**: `OpenACPCore` method signatures stay the same. Only internal delegation changes.
- **No config changes**: No new config fields.
- **Plugin API**: New middleware hooks are additive. Existing hooks unchanged.
- **Import paths**: New files are internal to core. No external consumers affected.
- **Speech plugin**: Existing `speechService` import in Session/SessionFactory removed. Speech plugin must register middleware during `setup()`. If speech plugin is not loaded, voice features are silently disabled (same as today).
- **Tunnel plugin**: Must register `message:afterTransform` middleware and `session:afterDestroy` middleware during `setup()`. If tunnel plugin is not loaded, no viewer links generated (same as today).
## Testing Strategy
Each phase includes:
1. **Move existing tests** — tests that cover extracted logic follow to new file's test suite
2. **Add integration test** — verify the delegation chain (Core → Handler → result) works
3. **Run full test suite** — `pnpm test` must pass after each phase
## File Changes Summary
| Phase | New Files | Modified Files |
|-------|-----------|---------------|
| 1 | `core/agent-switch-handler.ts`, `core/instance/` (4 files moved + index.ts) | `core/core.ts`, `core/sessions/session-factory.ts`, all files importing `instance-*` |
| 2 | None | `core/sessions/session.ts`, `core/sessions/session-factory.ts`, `plugins/speech/` (middleware registration) |
| 3 | None | `core/message-transformer.ts`, `core/core.ts`, `core/sessions/session-bridge.ts`, `core/sessions/session-factory.ts`, `plugins/tunnel/` (middleware registration) |

View File

@ -1,231 +0,0 @@
# Spec 3: SSE Adapter Plugin
**Date:** 2026-03-31
**Status:** Draft
**Related specs:**
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
## Overview
A standalone messaging adapter plugin (`@openacp/sse-adapter`) that provides full bidirectional communication for app clients. Uses SSE (Server-Sent Events) for server→client streaming and REST endpoints for client→server actions. Operates as a first-class adapter like Telegram — goes through the full middleware chain.
## Plugin Structure
```
src/plugins/sse-adapter/
index.ts — Plugin definition, setup/teardown
adapter.ts — SSEAdapter implements IChannelAdapter
connection-manager.ts — SSE connection lifecycle, session binding
routes.ts — Fastify plugin registered via ApiServerService
event-serializer.ts — OutgoingMessage → SSE event format
event-buffer.ts — Circular buffer for reconnect support
```
## Plugin Definition
```typescript
const plugin: OpenACPPlugin = {
name: '@openacp/sse-adapter',
version: '1.0.0',
description: 'SSE-based messaging adapter for app clients',
permissions: ['services:register', 'kernel:access', 'events:read'],
dependencies: ['@openacp/api-server'],
};
```
## Adapter Design
SSEAdapter implements `IChannelAdapter` directly. It does not extend `MessagingAdapter` (which is for rich messaging platforms with SendQueue, DraftManager, rendering logic). SSE clients handle their own rendering.
```typescript
class SSEAdapter implements IChannelAdapter {
name = 'sse';
capabilities = {
streaming: true,
richFormatting: false, // client renders
threads: true, // each session = 1 "thread"
reactions: false,
fileUpload: false, // v2
voice: false, // v2
};
// Outgoing — serialize and push to SSE connections
sendMessage(sessionId: string, message: OutgoingMessage): void;
sendPermissionRequest(sessionId: string, request: PermissionRequest): void;
sendNotification(sessionId: string, notification: NotificationMessage): void;
// Session threads — sessionId is the threadId
createSessionThread(sessionId: string): Promise<string>;
renameSessionThread(sessionId: string, name: string): Promise<void>;
// Lifecycle
start(): Promise<void>;
stop(): Promise<void>;
}
```
**Full OutgoingMessage support:** All message types are serialized and streamed — text, thought, tool_call, tool_update, plan, usage, error, attachment, system_message, session_end, mode_change, config_update, model_update, user_replay, resource, resource_link. Client decides what to render.
## Connection Manager
Manages SSE connections, each bound to a specific session.
```typescript
interface SSEConnection {
id: string; // unique connection ID
sessionId: string; // bound session
tokenId: string; // auth token ID (for revocation check)
response: ServerResponse; // SSE response stream
connectedAt: Date;
lastEventId?: string; // for reconnect, resume missed events
}
class ConnectionManager {
private connections: Map<string, SSEConnection>; // connectionId → connection
private sessionIndex: Map<string, Set<string>>; // sessionId → connectionIds
addConnection(sessionId: string, tokenId: string, res: ServerResponse): SSEConnection;
removeConnection(connectionId: string): void;
getConnectionsBySession(sessionId: string): SSEConnection[];
broadcast(sessionId: string, event: SSEEvent): void;
disconnectByToken(tokenId: string): void; // on token revocation
cleanup(): void;
}
```
**Multi-connection:** Multiple clients can connect to the same session (e.g., viewing output on 2 devices). All receive the same events.
**Connection lifecycle:**
1. Client `GET /api/v1/sse/sessions/:id/stream?token=<jwt>` → auth verify → create connection
2. Server sends `event: connected` with connection info
3. Server streams OutgoingMessages for that session
4. Heartbeat every 30s (`event: heartbeat`)
5. Client disconnect or token revoked → cleanup connection
## SSE Event Format
```
event: message
id: evt_001
data: {"type":"text","sessionId":"sess_123","content":"Hello world","timestamp":"2026-03-31T14:30:00Z"}
event: message
id: evt_002
data: {"type":"tool_call","sessionId":"sess_123","content":{"name":"Read","status":"running"},"timestamp":"..."}
event: permission_request
id: evt_003
data: {"sessionId":"sess_123","id":"perm_1","description":"Run npm install","options":[{"id":"allow","label":"Allow","isAllow":true},{"id":"deny","label":"Deny","isAllow":false}]}
event: session_update
id: evt_004
data: {"sessionId":"sess_123","status":"finished","name":"Fix auth bug"}
event: notification
id: evt_005
data: {"sessionId":"sess_123","type":"completed","summary":"Task finished"}
event: heartbeat
data: {"timestamp":"2026-03-31T14:30:00Z","uptime":3600}
event: connected
data: {"connectionId":"conn_abc","sessionId":"sess_123","connectedAt":"..."}
event: error
data: {"code":"EVENTS_LOST","missedCount":42}
```
## REST Endpoints (Client → Server)
Registered via `ApiServerService.registerPlugin('/api/v1/sse', routePlugin)`:
| Method | Path | Description | Scopes |
|--------|------|-------------|--------|
| `GET` | `/sessions/:id/stream` | SSE event stream (`?token=<jwt>`) | `sessions:read` |
| `POST` | `/sessions/:id/prompt` | Send message/prompt | `sessions:prompt` |
| `POST` | `/sessions/:id/permission` | Resolve permission request | `sessions:permission` |
| `POST` | `/sessions/:id/cancel` | Cancel session | `sessions:write` |
| `POST` | `/sessions/:id/command` | Execute command in session context | `commands:execute` |
| `GET` | `/connections` | List active SSE connections | `system:admin` |
## Message Flow
### Incoming (Client → Agent)
```
Client POST /api/v1/sse/sessions/:id/prompt
→ Fastify auth preHandler → verify JWT/secret
→ requireScopes('sessions:prompt')
→ Route handler
→ Middleware chain: message:incoming (security, rate limit, context...)
→ session.enqueuePrompt(message)
→ Agent processes prompt
```
### Outgoing (Agent → Client)
```
AgentInstance emits event
→ SessionBridge
→ Middleware chain: agent:beforeEvent, message:outgoing
→ SSEAdapter.sendMessage(sessionId, outgoingMessage)
→ ConnectionManager.getConnectionsBySession(sessionId)
→ EventSerializer.serialize(outgoingMessage) → SSE format
→ Write to all connected SSE streams for that session
```
Both directions go through the full middleware chain — identical to Telegram adapter. Security, context, rate limiting plugins all apply.
## SessionBridge Integration
SSE adapter registers into core like any adapter:
```typescript
setup(ctx) {
const core = ctx.kernel.core;
const api = ctx.getService<ApiServerService>('api-server');
const connectionManager = new ConnectionManager();
const adapter = new SSEAdapter(connectionManager);
core.registerAdapter('sse', adapter);
// Register routes into API server
api.registerPlugin('/api/v1/sse', createRoutes(adapter, connectionManager));
}
```
When a session is created via SSE endpoint, core creates a SessionBridge with the SSE adapter. If a session already has a bridge with another adapter (e.g., Telegram), SSE can observe as read-only stream — no conflict.
## Event Buffer (Reconnect Support)
```typescript
class EventBuffer {
private buffers: Map<string, CircularBuffer<SSEEvent>>; // sessionId → events
private maxSize: number; // default 100 per session
push(sessionId: string, event: SSEEvent): void;
getSince(sessionId: string, lastEventId: string): SSEEvent[];
cleanup(sessionId: string): void;
}
```
**Reconnect flow:**
1. Client reconnects with `Last-Event-ID` header
2. Server looks up events in buffer since that ID
3. Events found → replay missed events, then resume live streaming
4. Events evicted (buffer full, >100 events missed) → send `event: error` with `{"code":"EVENTS_LOST","missedCount":N}` → client knows to do full state refresh
## Auth for SSE Connections
SSE uses `EventSource` API which doesn't support custom headers. Auth via query parameter:
```
GET /api/v1/sse/sessions/:id/stream?token=<jwt>
```
Server validates JWT from query param using the same auth middleware (cross-ref Spec 2). The `token` query param is only accepted on SSE stream endpoints, not on REST endpoints (which use `Authorization` header).
On token revocation, `ConnectionManager.disconnectByToken(tokenId)` closes all SSE connections using that token.

View File

@ -1,159 +0,0 @@
# OpenACP Startup UX Improvements
## Problem
Running `openacp` when a daemon is already running shows `Already running (PID 91753)` and exits with code 1. No useful information, no options. Users can't easily:
- See what instance/config is active
- Switch between foreground/background mode
- Know which instance (global vs local) resolved
## Changes
### 1. Rich status + interactive menu when daemon already running
When `startDaemon()` returns "already running" error, instead of printing it and exiting, show a rich status panel and interactive menu.
**TTY mode** (interactive terminal):
```
OpenACP is already running
PID: 91753
Instance: ~/.openacp (global)
Mode: daemon
Channels: telegram, discord
API: port 3000
[r] Restart [f] Restart in foreground
[s] Stop [l] View logs
[q] Quit
>
```
User presses a single key (no Enter needed), action executes immediately.
**Non-TTY mode** (pipe, CI, script):
```
OpenACP is already running (PID 91753)
Instance: ~/.openacp (global)
Mode: daemon
Channels: telegram, discord
API: port 3000
Use: openacp restart | openacp stop | openacp logs
```
Exits with code 0 (not an error — it's informational).
### 2. Instance clarity on startup
Every start/restart command prints which instance it resolved to:
```
Instance: ~/.openacp (global)
OpenACP daemon started (PID 91753)
```
When a local `.openacp` exists in cwd but global is being used (because no `--local` flag), show a hint:
```
Instance: ~/.openacp (global)
hint: local instance found at ./.openacp — use --local to use it
OpenACP daemon started (PID 91753)
```
Conversely, when local auto-detected:
```
Instance: ./project/.openacp (local)
OpenACP daemon started (PID 91753)
```
### 3. `openacp attach` command
New command that shows status then tails logs — a single command to "connect" to a running daemon:
```
openacp attach
```
Output:
```
OpenACP is running (PID 91753)
Instance: ~/.openacp (global)
Channels: telegram, discord
--- logs (Ctrl+C to detach) ---
[2026-03-31 10:00:00] Session created: user123
[2026-03-31 10:00:01] Agent prompt received...
```
If not running, prints "OpenACP is not running." and exits with code 1.
Respects instance flags: `openacp --local attach`, `openacp --dir /path attach`.
### 4. Smart default (`openacp` with no args)
Current flow:
```
no config → setup wizard
config exists, daemon mode → start daemon (error if running)
config exists, foreground mode → start foreground
```
New flow:
```
no config → setup wizard
daemon already running → rich status + interactive menu (change #1)
config exists, daemon mode → start daemon
config exists, foreground mode → start foreground
```
The key change: check if daemon is running BEFORE trying to start, and show the rich status panel instead of an error.
### 5. Restart with mode flags
`openacp restart` gains `--foreground` and `--daemon` flags:
```
openacp restart --foreground # stop daemon, start in foreground
openacp restart --daemon # stop (fg or daemon), start as daemon
```
Without flags, restarts in same mode as currently configured.
When `--foreground` is used, the restart command stops the daemon then starts the server in foreground mode (attached to terminal). This is equivalent to `openacp stop && openacp --foreground` but in one command.
## Implementation scope
### Files to modify
- `src/cli/commands/default.ts` — smart default flow, instance hints
- `src/cli/daemon.ts` — extract rich status display logic
- `src/cli/commands/start.ts` — instance clarity hints
- `src/cli/commands/restart.ts` — add `--foreground` / `--daemon` flags
- `src/cli/commands/status.ts` — reuse `readInstanceInfo` for rich display
- `src/cli/commands/help.ts` — add `attach` command, document new flags
### Files to create
- `src/cli/commands/attach.ts` — new attach command
- `src/cli/instance-hint.ts` — shared instance clarity logic (print which instance, local hint)
- `src/cli/interactive-menu.ts` — TTY keypress menu utility
### Files to update for routing
- `src/cli.ts` — route `attach` command, pass instance info
## Edge cases
1. **PID file exists but process dead** — already handled by `isProcessRunning()` which cleans stale PID files. Menu won't show; normal start proceeds.
2. **Foreground process running (no PID file)** — no PID file means `isProcessRunning` returns false. Can't detect. This is existing behavior and acceptable — foreground mode ties to the terminal.
3. **Multiple instances** — each command respects `--local`/`--global`/`--dir` flags. The hint system only compares cwd local vs global, not all registered instances.
4. **Non-TTY + interactive menu** — falls back to info-only display with command suggestions.
5. **`openacp start` when already running** — keeps current behavior (error), but with richer info. The interactive menu only applies to the bare `openacp` command.
6. **`openacp restart --foreground` in non-TTY** — works fine, foreground process writes to stdout/stderr which may be redirected.
## Non-goals
- No changes to the setup wizard flow
- No changes to auto-start/LaunchAgent/systemd behavior
- No changes to `openacp stop` behavior
- No new config fields

View File

@ -1,280 +0,0 @@
# Session Config Options — Unified ACP Configuration
**Date:** 2026-04-01
**Approach:** A (Config-First) — migrate fully to ACP Config Options as single source of truth
## Overview
Replace all separate session state fields (`currentMode`, `availableModes`, `currentModel`, `availableModels`, `dangerousMode`) with a unified `configOptions: ConfigOption[]` backed by the ACP Session Config Options protocol. Expose config options to users via dedicated chat commands, REST API, and CLI.
## ACP Protocol Reference
ACP Config Options (`session/set_config_option`) supersede the older Session Modes API. Key properties:
- Agent declares `configOptions[]` in session initialization response
- Each option: `{ id, name, description?, category?, type: "select", currentValue, options[] }`
- Categories (UX only): `mode`, `model`, `thought_level`, `_custom_*`
- `setSessionConfigOption` response returns **complete** config state (enables cascading changes)
- `config_option_update` notification also returns full state
- Agents must provide defaults; clients display options in agent-provided order
## Section 1: Session State Migration
### Fields removed from Session
```
- currentMode?: string
- availableModes: SessionMode[]
- currentModel?: string
- availableModels: ModelInfo[]
- dangerousMode: boolean
```
### Fields added/changed on Session
```typescript
configOptions: ConfigOption[] // single source of truth from agent
clientOverrides: { // client-side state, not from agent
bypassPermissions?: boolean // fallback when agent has no permission mode
}
```
### SessionRecord changes
```typescript
// Removed:
- dangerousMode?: boolean
- acpState.currentMode
- acpState.availableModes
- acpState.currentModel
- acpState.availableModels
// Added/changed:
+ clientOverrides?: { bypassPermissions?: boolean }
// acpState simplified:
+ acpState?: {
configOptions?: ConfigOption[]
agentCapabilities?: AgentCapabilities // kept as-is
}
```
### Helper methods on Session
- `getConfigOption(id: string): ConfigOption | undefined`
- `getConfigByCategory(category: string): ConfigOption | undefined`
- `getConfigValue(id: string): string | undefined` — shortcut for currentValue
- `setInitialConfigOptions(options: ConfigOption[])` — replaces `setInitialAcpState()`
- `updateConfigOptions(options: ConfigOption[])` — receives full state from agent, replaces entire array
### Data migration
Old SessionRecords with `dangerousMode: true` and no `clientOverrides` are automatically migrated when loaded:
- `dangerousMode: true` → `clientOverrides: { bypassPermissions: true }`
- Old `acpState.currentMode/availableModes/currentModel/availableModels` fields are dropped (agent sends fresh state on resume)
## Section 2: Commands
### 4 dedicated commands (system commands, registered in core)
| Command | Category match | Fallback |
|---------|---------------|----------|
| `/mode` | `category: "mode"` | "Agent does not support mode selection" |
| `/model` | `category: "model"` | "Agent does not support model selection" |
| `/thought` | `category: "thought_level"` | "Agent does not support thought level" |
| `/dangerous` | Scan mode options for bypass values | Toggle `clientOverrides.bypassPermissions` |
### Flow for `/mode`, `/model`, `/thought`
1. Find config option by category in `session.configOptions`
2. Not found → return error message
3. Found → display menu with options (name + description), highlight currentValue
4. User selects → fire `config:beforeChange` middleware hook (plugin can block)
5. Call `agent.setConfigOption(configId, value)`
6. Receive full config state → `session.updateConfigOptions(newOptions)`
### Flow for `/dangerous`
1. Find config option with `category: "mode"` in `session.configOptions`
2. In that option's values, find one related to permission bypass (scan name/description for keywords: "bypass", "dangerous", "skip permission", etc.)
3. **Found** → call `setConfigOption(modeConfigId, bypassValue)` to switch agent to bypass mode
4. **Not found** → toggle `session.clientOverrides.bypassPermissions` (client-side fallback), inform user: "Agent does not support native permission bypass, using client-side auto-approve"
### Permission check logic (in session-bridge)
```typescript
// Known permission-bypass values (matched case-insensitively against option value/name)
const BYPASS_KEYWORDS = ["bypass", "dangerous", "skip", "dontask", "dont_ask", "auto_accept"];
function isPermissionBypass(value: string): boolean {
const lower = value.toLowerCase();
return BYPASS_KEYWORDS.some(kw => lower.includes(kw));
}
// 1. Agent-side: check if mode config option's currentValue is a bypass mode
const modeOption = session.getConfigByCategory("mode");
const isBypassMode = modeOption && isPermissionBypass(modeOption.currentValue);
// 2. Client-side fallback
const isClientBypass = session.clientOverrides.bypassPermissions;
if (isBypassMode || isClientBypass) {
// auto-approve permission request
}
```
## Section 3: API Server & CLI
### REST API routes (api-server plugin)
| Method | Route | Description |
|--------|-------|-------------|
| `GET` | `/sessions/:id/config` | Get all config options + clientOverrides |
| `PUT` | `/sessions/:id/config/:configId` | Set config option → `setConfigOption()` → return full state |
| `GET` | `/sessions/:id/config/overrides` | Get clientOverrides |
| `PUT` | `/sessions/:id/config/overrides` | Set clientOverrides (bypassPermissions, etc.) |
Response format:
```json
{
"configOptions": [{ "id": "mode", "currentValue": "code", "..." : "..." }],
"clientOverrides": { "bypassPermissions": false }
}
```
### CLI commands
```bash
openacp session config <sessionId> # List all config options
openacp session config <sessionId> set <id> <value> # Set config option
openacp session config <sessionId> overrides # Show clientOverrides
openacp session config <sessionId> dangerous # Toggle bypassPermissions
```
All surfaces (chat commands, API, CLI) go through the same flow: Session → AgentInstance.setConfigOption() → receive full state → update session.
## Section 4: Event Flow & Bridge Updates
### Agent-initiated config update
```
Agent → config_option_update (full configOptions[])
→ AgentInstance emits AgentEvent { type: "config_option_update", options }
→ SessionBridge handles:
1. session.updateConfigOptions(options)
2. persistAcpState()
3. messageTransformer → adapter (notify user if needed)
```
### User-initiated config change
```
User → /mode code
→ Command handler finds config option by category "mode"
→ Fire config:beforeChange middleware hook (can block)
→ agent.setConfigOption("mode", "code")
→ Agent response: full configOptions[]
→ session.updateConfigOptions(newOptions) (no hook — already validated before send)
→ persistAcpState()
```
### Session resume flow
```
1. Load SessionRecord → cache configOptions + clientOverrides
2. session.setInitialConfigOptions(record.acpState.configOptions)
3. session.clientOverrides = record.clientOverrides
4. Agent connects → sends fresh configOptions in initialSessionResponse
5. Fresh state overrides cache (agent is source of truth)
```
### Middleware hooks
- Keep `config:beforeChange` as the single hook for all config changes
- Remove `mode:beforeChange` and `model:beforeChange` (superseded)
- Hook fires once before sending to agent (user-initiated), and once when agent pushes update
## Section 5: Backward Compatibility & Migration
### Data migration (automatic on SessionStore load)
- `dangerousMode: true` → `clientOverrides: { bypassPermissions: true }`
- Old `acpState.currentMode/availableModes/currentModel/availableModels` → dropped
### Code cleanup
**Session class:**
- Remove: `currentMode`, `availableModes`, `currentModel`, `availableModels`, `dangerousMode`
- Remove: `updateMode()`, `updateModel()`, `setInitialAcpState()`
- Add: `configOptions`, `clientOverrides`, `getConfigOption()`, `getConfigByCategory()`, `getConfigValue()`, `setInitialConfigOptions()`, updated `updateConfigOptions()`
**SessionRecord:**
- Remove: `dangerousMode`, `acpState.currentMode/availableModes/currentModel/availableModels`
- Add: `clientOverrides`
**AgentInstance:**
- Remove: `setMode()`, `setModel()` — use `setConfigOption()` only
**AgentEvent types:**
- Remove: `current_mode_update`, `model_update` events
- Keep: `config_option_update` as the single event for all config changes
**SessionBridge:**
- Remove: separate case handlers for `current_mode_update`, `model_update`
- Consolidate into `config_option_update` handler
- Update permission check to use `getConfigByCategory("mode")` + `clientOverrides.bypassPermissions`
**Middleware hooks (plugin/types.ts):**
- Remove: `mode:beforeChange`, `model:beforeChange`
- Keep: `config:beforeChange`
**Plugin template:** Update `cli/plugin-template/` to reflect new middleware hooks.
**Tests:** Update all tests referencing removed fields/methods.
## Section 6: Platform UI Rendering
Commands (`/mode`, `/model`, `/thought`, `/dangerous`) return `CommandResponse` type `menu`. Each adapter renders menus using its native interactive elements.
### Command Response Format
All config commands return a `menu` response:
```typescript
{
type: 'menu',
title: 'Session Mode', // e.g. from configOption.name
options: [
{ label: '✅ Code', command: '/mode code', hint: 'Full tool access' },
{ label: 'Architect', command: '/mode architect', hint: 'Design without implementation' },
{ label: 'Ask', command: '/mode ask', hint: 'Ask permission before changes' },
]
}
```
- Current value prefixed with ✅
- `hint` populated from `ConfigOptionValue.description`
- `command` is the full command to execute when selected
### Telegram
- Inline keyboard: one button per option per row
- Callback data: `c/<command>` prefix (cache for >64 bytes)
- Existing pattern in `adapter.ts` `renderCommandResponse()` for `menu` type
### Discord
- `ActionRowBuilder<ButtonBuilder>`: one button per option
- Active option styled as `Primary`, others as `Secondary`
- Existing pattern in `renderCommandResponse()` + `buildMenuKeyboard()`
### Slack
- Block Kit: `actions` block with `button` elements
- Active option styled with confirm visual
- Existing pattern via blocks rendering
### Agent-Initiated Updates (Notifications)
When agent pushes `config_option_update`, the bridge notifies user via adapter:
- **Config change text**: "Mode changed to **Code**" / "Model switched to **opus-4**"
- No buttons on notifications — user can use commands to change back
- Renderer methods: update existing `renderModeChange()`, `renderModelUpdate()`, `renderConfigUpdate()` to read from configOptions instead of separate fields
### No Config = No Buttons
If agent provides no configOptions, commands return error text. No empty menus or placeholder buttons are shown.

View File

@ -1,608 +0,0 @@
# Spec 5: Tunnel Auto-Start, Auth One-Time Code, Display Updates
**Date:** 2026-04-01
**Status:** Draft
**Related specs:**
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
- [Spec 3: SSE Adapter](./2026-03-31-sse-adapter-design.md)
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
## Overview
Three updates to the existing specs:
1. **One-time code auth** — Replace JWT-in-URL with a short-lived, single-use code that exchanges for a JWT. Prevents link reuse.
2. **Tunnel auto-start + keepalive** — Server boot auto-creates tunnel when `tunnel.enabled: true`. HTTP keepalive ping detects dead tunnels. Merge viewer server into API server (1 port, 1 tunnel).
3. **Terminal display** — Copyable links outside Unicode boxes in both startup and `openacp remote` output.
## 1. One-Time Code Auth
### Changes to Spec 2 (Auth System)
#### Data Model
```typescript
interface StoredCode {
code: string; // 32-char random hex (crypto.randomBytes(16))
role: string; // admin | operator | viewer
scopes?: string[]; // optional scope override
name: string; // "remote-14h30-01-04-2026"
expire: string; // JWT expire duration when exchanged (e.g. "24h")
createdAt: string; // ISO 8601
expiresAt: string; // createdAt + 30 minutes
used: boolean; // true after successful exchange
}
```
#### Storage
Stored in existing `TokenStore` — add `codes: Map<string, StoredCode>` alongside `tokens: Map<string, StoredToken>`. Persisted in same `tokens.json` file with a new `codes` array field.
#### New Endpoints
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| `POST` | `/api/v1/auth/codes` | Generate one-time code | Secret token only |
| `POST` | `/api/v1/auth/exchange` | Exchange code for JWT | None (code is auth) |
| `GET` | `/api/v1/auth/codes` | List active (unused, unexpired) codes | `auth:manage` |
| `DELETE` | `/api/v1/auth/codes/:code` | Revoke unused code | `auth:manage` |
#### Generate Code
```
POST /api/v1/auth/codes
Authorization: Bearer <secret-token>
Body: {
"role": "admin",
"name": "remote-14h30-01-04-2026",
"expire": "24h",
"scopes": ["sessions:read", "sessions:prompt"] // optional
}
Response: {
"code": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
"expiresAt": "2026-04-01T15:00:00Z"
}
```
#### Exchange Code for JWT
```
POST /api/v1/auth/exchange
Body: {
"code": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"
}
Success Response (200): {
"accessToken": "eyJ...",
"tokenId": "tok_abc123",
"expiresAt": "2026-04-02T14:30:00Z",
"refreshDeadline": "2026-04-08T14:30:00Z"
}
Error Responses:
401: { "error": { "code": "INVALID_CODE", "message": "Code is invalid, expired, or already used" } }
429: { "error": { "code": "RATE_LIMITED", "message": "Too many attempts" } }
```
Exchange flow:
1. Look up code in store
2. Check: exists? `used === false`? `expiresAt > now`?
3. **Atomically** mark `code.used = true` (synchronous in single event loop tick — no async gap between check and mark)
4. Create `StoredToken` with role/scopes/expire from the code
5. Sign and return JWT
#### Race Condition Handling
Two clients exchanging the same code concurrently: the check (`used === false`) and mark (`used = true`) happen synchronously in the same event loop tick. No `await` between them. First caller wins, second gets 401.
#### Rate Limiting
`/auth/exchange` rate limited to **10 requests per minute per IP** via Fastify rate limiter config. Prevents brute-force guessing of codes.
#### Cleanup
Expired (`expiresAt < now`) and used codes cleaned up hourly, same schedule as token cleanup.
#### Auth Middleware Update
`/auth/exchange` must bypass auth middleware — it's the one endpoint that accepts no auth header (the code in the body IS the credential). Add to auth middleware's skip list alongside `/api/v1/system/health`.
#### Existing JWT Flow Preserved
`POST /api/v1/auth/tokens` still works for programmatic access (CLI tools, scripts, automation). One-time codes are specifically for `openacp remote` → human use via URL.
### Changes to Spec 4 (App Connectivity)
#### `openacp remote` Flow Update
```
openacp remote
→ (same instance/health checks as before)
→ Read secret token from <instanceRoot>/api-secret
→ POST /api/v1/auth/codes // was: /auth/tokens
→ Authorization: Bearer <secret-token>
→ Body: { role: "admin", expire: "24h", name: "remote-14h30-01-04-2026" }
→ Receive { code, expiresAt }
→ Generate links with ?code= instead of ?token=
→ Display output
```
#### Link Formats Update
```
Local:
http://localhost:21420?code=a1b2c3d4e5f6...
Tunnel:
https://abc-123.trycloudflare.com?code=a1b2c3d4e5f6...
App:
openacp://connect?host=abc-123.trycloudflare.com&code=a1b2c3d4e5f6...
```
#### App Connection Flow Update (Remote — Case 2)
```
User pastes link or scans QR code
→ App parses URL → extract host + code
→ POST {host}/api/v1/auth/exchange
→ Body: { code: "a1b2c3d4..." }
→ 200: receive JWT → store in secure storage
→ 401: code invalid/expired/used → show error + prompt re-enter
→ 429: rate limited → show "try again later"
→ Network error: host unreachable → show error
→ Clear code from URL/history
→ Use JWT Authorization header for all subsequent requests
→ Connect SSE stream
→ Ready
```
#### Custom Scheme Update (Case 3)
```
openacp://connect?host=abc-123.trycloudflare.com&code=a1b2c3d4...
→ OS opens app → parse host + code
→ POST {host}/api/v1/auth/exchange → same as Case 2
```
#### Local Auto-Discover (Case 1) — Unchanged
Local connections still use `api-secret` file directly. No code needed.
## 2. Tunnel Auto-Start + Keepalive + Viewer Server Merge
### Merge Viewer Server into API Server
#### Current Architecture (2 servers, 2 ports)
```
Tunnel plugin: Hono viewer server (port 3100)
/view/:id, /diff/:id, /output/:id — HTML viewers
/api/file/:id, /api/diff/:id — JSON APIs for viewers
/health — health check
API server: Fastify (port 21420)
/api/v1/* — REST API + SSE
/api/docs — Swagger
/* — Static dashboard (SPA fallback)
```
Problem: 2 tunnels needed for remote access → Cloudflare free tier rate limiting risk on tunnel creation.
#### New Architecture (1 server, 1 port)
```
API server: Fastify (port 21420)
/api/v1/* — REST API + SSE
/api/docs — Swagger
/view/:id — file viewer (registered by tunnel plugin, no auth)
/diff/:id — diff viewer (registered by tunnel plugin, no auth)
/output/:id — output viewer (registered by tunnel plugin, no auth)
/api/file/:id — JSON file API (registered by tunnel plugin, no auth)
/api/diff/:id — JSON diff API (registered by tunnel plugin, no auth)
/* — Static dashboard (SPA fallback via notFoundHandler)
```
One tunnel exposes everything.
#### Viewer Routes Registration
Tunnel plugin registers viewer routes via `ApiServerService.registerPlugin()`:
```typescript
// In tunnel plugin setup()
const api = ctx.getService<ApiServerService>('api-server');
const viewerRoutes = createViewerRoutes(store);
api.registerPlugin('/', viewerRoutes, { auth: false });
```
Routes registered with `{ auth: false }` — viewer links are public share links sent in chat messages. They must be accessible without JWT.
**Route priority:** Fastify registered routes match BEFORE `setNotFoundHandler` (static server SPA fallback). No conflict with dashboard.
**`/api/file/:id` and `/api/diff/:id` naming:** These are in `/api/` namespace but NOT `/api/v1/`. No conflict with API routes. Keeping existing names avoids modifying HTML templates.
**Prefix `/` verification:** If Fastify doesn't support `registerPlugin('/', ...)` correctly, fallback: register routes directly on `server.app` via a new `registerRootPlugin()` method on ApiServerService.
#### Files Changed in Tunnel Plugin
| File | Change |
|------|--------|
| `server.ts` | **Delete** — Hono viewer server removed |
| `viewer-routes.ts` | **New** — Fastify plugin with viewer routes |
| `tunnel-service.ts` | Remove Hono server boot, accept `apiPort` param, update `getPublicUrl()` fallback |
| `index.ts` | Add `@openacp/api-server` dependency, register viewer routes, auto-connect on `system:ready` |
#### TunnelService Changes
```typescript
// Before
async start(): Promise<string> {
// Boot Hono server on tunnel.port
// Register system tunnel pointing to Hono server port
}
// After
async start(apiPort: number): Promise<string> {
// No server to boot — viewer routes already registered in API server
// Register system tunnel pointing to apiPort
this.apiPort = apiPort;
// ...register tunnel via TunnelRegistry.add(apiPort, provider, options)
}
getPublicUrl(): string {
const system = this.registry.getSystemEntry();
return system?.publicUrl || `http://localhost:${this.apiPort}`;
}
```
**Interface update in `core/plugin/types.ts`:**
```typescript
// Before
start(): Promise<string>
// After
start(apiPort: number): Promise<string>
```
Not a breaking change for external plugins — only core calls `start()`.
#### Degraded Mode (No API Server)
If `@openacp/api-server` is disabled:
- Viewer routes not registered → viewer URLs won't resolve
- `fileUrl()`, `diffUrl()`, `outputUrl()` return empty string (not broken localhost URL)
- Log warning: "Viewer links unavailable without API server plugin"
- User tunnels (`/tunnel <port>`) still work (tunnel arbitrary ports)
#### Config Deprecations
| Field | Status | Behavior |
|-------|--------|----------|
| `tunnel.port` | Deprecated | Ignored. Log warning if user sets it. Kept in Zod schema with `.optional()` for backward compat. |
| `tunnel.auth.enabled` | Deprecated | Ignored. Same treatment. |
| `tunnel.auth.token` | Deprecated | Ignored. Same treatment. |
Remove deprecated fields from schema after 2 releases.
#### Dependencies Removed
- `hono`
- `@hono/node-server`
### Auto-Start on Server Boot
When `tunnel.enabled: true` and server starts:
```
tunnel plugin setup():
→ Check @openacp/api-server dependency available
→ Register viewer routes via ApiServerService
→ Listen for system:ready event
system:ready fires:
→ tunnel.enabled === true?
→ Provider configured in config?
→ Yes → apiPort = ApiServerService.getPort()
→ TunnelService.start(apiPort)
→ TunnelRegistry.add(apiPort, provider, options)
→ Success → log "Tunnel ready → {url}"
→ Fail → existing retry logic (exponential backoff, max 5)
→ No provider → log warning "Tunnel enabled but no provider configured. Run: openacp remote"
→ enabled === false → skip (no tunnel)
```
**Startup timeout:** Tunnel creation is awaited for up to **30 seconds** during startup. If not ready in 30s, startup display shows "Tunnel: connecting..." and tunnel continues connecting in background. When ready, logs URL separately.
### Keepalive Ping
#### TunnelKeepAlive Class
```typescript
// New file: plugins/tunnel/keepalive.ts
class TunnelKeepAlive {
private interval: NodeJS.Timeout | null = null;
private consecutiveFails = 0;
private static readonly PING_INTERVAL = 30_000; // 30 seconds
private static readonly FAIL_THRESHOLD = 3; // 3 consecutive fails = dead
private static readonly PING_TIMEOUT = 5_000; // 5s per ping
start(tunnelUrl: string, onDead: () => void): void {
this.stop(); // clear any existing interval
this.consecutiveFails = 0;
this.interval = setInterval(async () => {
try {
const res = await fetch(`${tunnelUrl}/api/v1/system/health`, {
signal: AbortSignal.timeout(TunnelKeepAlive.PING_TIMEOUT),
});
if (res.ok) {
this.consecutiveFails = 0;
} else {
this.consecutiveFails++;
}
} catch {
this.consecutiveFails++;
}
if (this.consecutiveFails >= TunnelKeepAlive.FAIL_THRESHOLD) {
this.stop();
onDead();
}
}, TunnelKeepAlive.PING_INTERVAL);
}
stop(): void {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
this.consecutiveFails = 0;
}
}
```
#### Integration with TunnelRegistry
```
Tunnel entry status → 'active' (new tunnel established):
→ Start keepalive with tunnel's publicUrl
→ onDead callback:
→ Clear publicUrl from entry (getPublicUrl() falls back to localhost)
→ Kill tunnel process (SIGTERM)
→ Existing retry logic creates new tunnel
→ New tunnel active → start new keepalive with new URL
Process exit detected (existing onExit handler):
→ Stop keepalive (prevent pinging dead URL)
→ Existing retry logic handles reconnection
→ New tunnel active → start new keepalive
TunnelRegistry.stop() or shutdown():
→ Stop keepalive
→ Normal shutdown flow
Keepalive ONLY applies to:
→ System tunnel (type='system')
→ NOT user tunnels (type='user') — user tunnels are ephemeral
```
#### Timing: Keepalive Start
Keepalive starts AFTER both conditions are met:
1. Tunnel is active (has publicUrl)
2. API server is listening (health endpoint returns 200)
If keepalive starts before API server is ready, pings would fail and false-trigger a restart. The `system:ready` event guarantees both are ready.
#### URL Change on Tunnel Restart
Cloudflare free tier generates a new subdomain on each tunnel creation. After keepalive kills + retry:
1. Old URL is dead → cleared from entry
2. `getPublicUrl()` temporarily returns localhost fallback
3. New tunnel establishes → new URL stored in entry
4. Keepalive restarts with new URL
5. New viewer links use new URL automatically (MessageTransformer calls `getPublicUrl()` per-message)
**Existing viewer links with old URL become broken** — this is expected and acceptable. Viewer entries have 60-minute TTL anyway.
## 3. Terminal Display Updates
### Startup Display (main.ts)
**New format — status in checkmarks, links as plain text below:**
```
✓ Config loaded
✓ Dependencies checked
✓ Tunnel ready
✓ Telegram connected
✓ API server on port 21420
Local: http://localhost:21420
Tunnel: https://abc-123.trycloudflare.com
OpenACP is running. Press Ctrl+C to stop.
```
**Tunnel still connecting (>30s startup timeout):**
```
✓ Config loaded
✓ Dependencies checked
⟳ Tunnel connecting...
✓ Telegram connected
✓ API server on port 21420
Local: http://localhost:21420
OpenACP is running. Press Ctrl+C to stop.
```
When tunnel connects later, log: `✓ Tunnel ready → https://...`
**Tunnel disabled or failed:**
```
✓ Config loaded
✓ Dependencies checked
✓ Telegram connected
✓ API server on port 21420
Local: http://localhost:21420
OpenACP is running. Press Ctrl+C to stop.
```
No Tunnel line — only shown when URL is available.
**Tunnel failed with error:**
```
✓ Config loaded
✓ Dependencies checked
⚠ Tunnel failed (rate limited) — retrying in background
✓ Telegram connected
✓ API server on port 21420
Local: http://localhost:21420
OpenACP is running. Press Ctrl+C to stop.
```
**Non-TTY (piped output):** No colors, no box, no spinner. Just raw lines for machine parsing.
### `openacp remote` Output
**New format — metadata in box, links as plain text:**
```
┌────────────────────────────────────────────────────────────┐
│ Remote Access │
├────────────────────────────────────────────────────────────┤
│ Token: remote-14h30-01-04-2026 │
│ Role: admin │
│ Expires: 2026-04-02 14:30 (24h) │
└────────────────────────────────────────────────────────────┘
Local:
http://localhost:21420?code=a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
Tunnel:
https://abc-123.trycloudflare.com?code=a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
App:
openacp://connect?host=abc-123.trycloudflare.com&code=a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
██████████████████████
██ QR (tunnel link) ██
██████████████████████
⚠ Code expires in 30 minutes and can only be used once.
```
**Key changes from Spec 4:**
- Links use `?code=` instead of `?token=`
- Links are plain text outside the box — each URL on its own line, label above
- Easy to triple-click select entire URL
- Warning at bottom about code expiry and single-use
- QR code encodes tunnel link (or local link if `--no-tunnel`)
**No tunnel available:**
```
┌────────────────────────────────────────────────────────────┐
│ Remote Access │
├────────────────────────────────────────────────────────────┤
│ Token: remote-14h30-01-04-2026 │
│ Role: admin │
│ Expires: 2026-04-02 14:30 (24h) │
└────────────────────────────────────────────────────────────┘
Local:
http://localhost:21420?code=a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
⚠ Code expires in 30 minutes and can only be used once.
⚠ No tunnel available — local link only works on same machine.
```
**`--no-qr` flag:** QR block hidden.
**`--no-tunnel` flag:** Only Local link shown, no Tunnel/App links.
## 4. Summary of All File Changes
### New Files
| File | Description |
|------|-------------|
| `plugins/tunnel/viewer-routes.ts` | Fastify plugin — viewer HTML + JSON API routes |
| `plugins/tunnel/keepalive.ts` | TunnelKeepAlive class — HTTP ping loop |
### Modified Files
| File | Changes |
|------|---------|
| `plugins/api-server/routes/auth.ts` | Add `/codes` and `/exchange` endpoints |
| `plugins/api-server/auth/token-store.ts` | Add `codes` Map, persist in `tokens.json`, cleanup |
| `plugins/api-server/auth/types.ts` | Add `StoredCode` interface |
| `plugins/api-server/middleware/auth.ts` | Skip auth for `/auth/exchange` |
| `plugins/api-server/schemas/` | Add Zod schemas for code endpoints |
| `plugins/tunnel/tunnel-service.ts` | Remove Hono server boot, accept `apiPort`, update `getPublicUrl()` fallback |
| `plugins/tunnel/tunnel-registry.ts` | Integrate TunnelKeepAlive for system tunnel |
| `plugins/tunnel/index.ts` | Add `@openacp/api-server` dependency, register viewer routes, auto-connect on `system:ready` |
| `core/plugin/types.ts` | Update `TunnelServiceInterface.start(apiPort: number)` signature |
| `main.ts` | Update startup display format (links outside status list) |
| `cli/commands/remote.ts` | Use `/auth/codes`, output format with links outside box |
### Deleted Files
| File | Reason |
|------|--------|
| `plugins/tunnel/server.ts` | Hono viewer server replaced by Fastify routes |
### Dependencies
| Package | Change |
|---------|--------|
| `hono` | Remove |
| `@hono/node-server` | Remove |
### Files NOT Changed
| File | Why |
|------|-----|
| `core/message-transformer.ts` | Uses `TunnelServiceInterface` — interface preserved |
| `core/adapter-primitives/display-spec-builder.ts` | Same interface |
| `plugins/telegram/activity.ts` | Same `outputUrl()` / `getStore()` API |
| `plugins/tunnel/viewer-store.ts` | Unchanged — framework agnostic |
| `plugins/tunnel/templates/*` | Pure HTML strings — no framework dependency |
| `plugins/tunnel/providers/*` | Tunnel providers unchanged |
| `plugins/tunnel/tunnel-registry.ts` (core logic) | Retry logic unchanged, only add keepalive hooks |
## 5. Edge Cases
| Edge Case | Handling |
|-----------|----------|
| **Code replay** (same code used twice) | Synchronous check+mark in single event loop tick. First caller wins, second gets 401. |
| **Code expired** | `expiresAt < now` → 401. Cleaned up hourly. |
| **Code brute force** | Rate limit: 10 req/min per IP on `/auth/exchange`. |
| **Concurrent exchange race** | No async gap between `used` check and mark. Event loop guarantees atomicity. |
| **Viewer URLs with old port 3100** | Self-expire via 60-min TTL. No migration needed. |
| **Tunnel plugin without API server** | Log warning, viewer URLs return empty string, user tunnels still work. |
| **API server not ready when tunnel starts** | LifecycleManager dependency order: api-server boots before tunnel. |
| **Cloudflare URL changes after restart** | Keepalive stops, retry creates new tunnel with new URL, keepalive restarts. |
| **Keepalive false positive** (transient blip) | 3 consecutive fails threshold (90s window). |
| **Keepalive + process exit race** | `onExit` handler checks if already retrying, no double-retry. |
| **Startup tunnel slow (>30s)** | Display "⟳ Tunnel connecting...", log URL when ready. |
| **Fastify prefix `/` for viewer routes** | If unsupported, fallback: add `registerRootPlugin()` to ApiServerService. |
| **`/api/file/:id` naming in API server** | No conflict with `/api/v1/*`. Different prefix. Templates use relative URLs — still work. |
| **`tunnel.port` config set by old user** | Ignored + log deprecation warning. Schema keeps field as `.optional()`. |
| **`tunnel.auth.*` config set by old user** | Ignored + log deprecation warning. Schema keeps fields as `.optional()`. |
| **SSH/remote terminal copy** | Plain text links work reliably in all terminals. |
| **Non-TTY output** | No colors, no box. Raw URLs for machine parsing. |
| **Viewer route vs static server SPA** | Registered Fastify routes match before `setNotFoundHandler`. No conflict. |
| **`getPublicUrl()` during tunnel restart** | `publicUrl` cleared when tunnel fails. Returns localhost fallback until new tunnel active. |

View File

@ -1,246 +0,0 @@
# CLI `--json` Output Standardization
## Overview
Add standardized `--json` flag support across all CLI commands that return structured data or action results. When `--json` is passed, the command outputs a single line of JSON to stdout and exits with an appropriate exit code. This enables automation, scripting, and app integration.
## JSON Envelope
All commands use a consistent envelope:
**Success (exit 0):**
```json
{ "success": true, "data": { ... } }
```
**Error (exit non-zero):**
```json
{ "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable description" } }
```
Rules:
- Output is always a single line of valid JSON on stdout
- Exit code 0 for success, non-zero for errors
- No ANSI escape codes, progress bars, spinners, or other text in stdout when `--json` is active
## Core Module: `src/cli/output.ts`
### Types
```typescript
interface JsonSuccess<T = unknown> {
success: true;
data: T;
}
interface JsonError {
success: false;
error: {
code: string;
message: string;
};
}
type JsonOutput<T = unknown> = JsonSuccess<T> | JsonError;
```
### Functions
```typescript
function isJsonMode(args: string[]): boolean;
function jsonSuccess(data: unknown): never; // JSON to stdout + process.exit(0)
function jsonError(code: string, message: string): never; // JSON to stdout + process.exit(1)
function muteForJson(): void; // Mute pino logger to suppress stderr noise
```
`jsonSuccess` and `jsonError` are terminal — they call `process.exit()` and never return. This naturally prevents any subsequent `console.log` noise.
### Error Codes
```typescript
const ErrorCodes = {
DAEMON_NOT_RUNNING: 'DAEMON_NOT_RUNNING',
INSTANCE_NOT_FOUND: 'INSTANCE_NOT_FOUND',
PLUGIN_NOT_FOUND: 'PLUGIN_NOT_FOUND',
AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',
CONFIG_INVALID: 'CONFIG_INVALID',
CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',
SETUP_FAILED: 'SETUP_FAILED',
API_ERROR: 'API_ERROR',
TUNNEL_ERROR: 'TUNNEL_ERROR',
INSTALL_FAILED: 'INSTALL_FAILED',
UNINSTALL_FAILED: 'UNINSTALL_FAILED',
MISSING_ARGUMENT: 'MISSING_ARGUMENT',
UNKNOWN_COMMAND: 'UNKNOWN_COMMAND',
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
} as const;
```
New codes may be added as needed during implementation.
## Noise Handling
| Source | Stream | Solution |
|--------|--------|----------|
| Pino logger | stderr | Call `muteForJson()` at command start to suppress |
| `console.log` in commands | stdout | `jsonSuccess`/`jsonError` call `process.exit()`, so subsequent logs never execute |
| Progress bars (`process.stdout.write`) | stdout | Guard with `if (!json)` or place after `jsonSuccess` call |
| Spinners (ora) | stdout | Not used in CLI commands currently; guard if added |
### Command Pattern
```typescript
export async function cmdExample(args: string[], instanceRoot?: string): Promise<void> {
const json = isJsonMode(args);
if (json) muteForJson();
try {
// ... command logic ...
if (json) jsonSuccess(data); // exits, nothing below runs
// Human-readable output
console.log('...');
} catch (err) {
if (json) jsonError(ErrorCodes.SOME_ERROR, err.message); // exits
console.error('...');
process.exit(1);
}
}
```
## Commands In Scope
### Group A — Data/Query Commands
| Command | `data` shape |
|---------|-------------|
| `agents list` | `{ agents: [{ key, name, version, distribution, description, installed, available, missingDeps }] }` |
| `agents info <key>` | `{ key, name, version, distribution, description, installed, binaryPath?, command?, registryId? }` |
| `plugins` / `plugin list` | `{ plugins: [{ name, version, enabled, source, description }] }` |
| `plugin search <q>` | `{ results: [{ name, version, description }] }` |
| `status` | `{ instances: [{ id, name, status, pid, dir, mode, channels, apiPort, tunnelPort }] }` |
| `status --id <id>` | `{ id, name, status, pid, dir, mode, channels, apiPort, tunnelPort }` |
| `config set <k> <v>` | `{ path, value, needsRestart }` |
| `doctor --json` | `{ categories: [{ name, results: [{ status, message }] }], summary: { passed, warnings, failed } }` |
| `tunnel list` | `{ tunnels: [{ port, label?, publicUrl?, status }] }` |
| `api *` (20+ subcommands) | Normalized wrap of API response |
| `version` | `{ version: "2026.401.1" }` |
Notes:
- `config` (no args) opens interactive editor — not JSON-compatible. Only `config set` supports `--json`.
- `doctor --json` implies `--dry-run` (no interactive fix prompts). Reports checks only. Always exits 0 with `success: true` — caller checks `summary.failed` to determine health.
### Group B — Action/Result Commands
| Command | `data` shape |
|---------|-------------|
| `start` | `{ pid, instanceId, dir }` |
| `stop` | `{ stopped: true, pid }` |
| `restart` | `{ pid, instanceId, dir }` |
| `install <plugin>` | `{ plugin, version, installed: true }` |
| `uninstall <plugin>` | `{ plugin, uninstalled: true }` |
| `agents install <key>` | `{ key, version, installed: true }` |
| `agents uninstall <key>` | `{ key, uninstalled: true }` |
| `setup` | `{ configPath }` |
| `adopt` | `{ sessionId, threadId, agent, status }` |
| `remote` | `{ code, name, role, expiresAt, urls: { local, tunnel?, app? } }` |
| `tunnel add` | `{ port, publicUrl }` |
| `tunnel stop` | `{ port, stopped: true }` |
| `tunnel stop-all` | `{ stopped: true }` |
| `plugin enable/disable` | `{ plugin, enabled: boolean }` |
Notes:
- `restart --foreground` starts a blocking server — incompatible with `--json`. When `--json` is passed, `restart` always uses daemon mode regardless of config.
- `plugin configure` and `plugin create` are interactive — not JSON-compatible.
### Out of Scope
`logs`, `attach`, `onboard`, `reset`, `dev`, `help`, `default`, `config` (interactive editor), `plugin configure`, `plugin create`, `agents run` — these are interactive, streaming, or blocking commands where JSON output is not applicable.
## Help Text
Commands that support `--json` must document it in their `--help` output. Add a line like:
```
--json Output result as JSON
```
## Migration: Existing `--json` Commands
Two commands already support `--json` with non-standard formats. Both will be migrated to the new envelope format.
**`agents list --json`** (breaking change):
- Before: `[{ key, name, ... }]` (raw array)
- After: `{ "success": true, "data": { "agents": [{ key, name, ... }] } }`
**`setup --json`** (breaking change):
- Before: `{ success: false, error: "string" }` / `{ success: true, configPath }`
- After: `{ "success": false, "error": { "code": "SETUP_FAILED", "message": "..." } }` / `{ "success": true, "data": { "configPath": "..." } }`
## Testing Strategy
### Layer 1: Unit Tests — `output.ts` helpers
File: `src/cli/commands/__tests__/output.test.ts`
- `isJsonMode()` returns correct boolean for various arg combinations
- `jsonSuccess()` outputs valid single-line JSON with `{ success: true, data }` and exits 0
- `jsonError()` outputs valid single-line JSON with `{ success: false, error: { code, message } }` and exits non-zero
- `muteForJson()` calls `muteLogger()`
- All `ErrorCodes` values are unique strings
### Layer 2: Integration Tests — per-command JSON output
File: `src/cli/commands/__tests__/json-output.test.ts`
For each command with `--json` support:
1. **Success case**: mock dependencies, call with `--json`, verify:
- Output is valid JSON (parseable by `JSON.parse`)
- `success === true`
- `data` matches expected shape
- Exit code 0
2. **Error case**: trigger error condition, verify:
- Output is valid JSON (not ANSI text or stack trace)
- `success === false`
- `error.code` is a known error code string
- `error.message` is a non-empty string
- Exit code non-zero
3. **No noise**: stdout contains exactly one line of JSON, no progress bars, ANSI codes, or extraneous text
### Layer 3: Contract Tests — JSON schema stability
File: `src/cli/commands/__tests__/json-contract.test.ts`
Snapshot-style tests that verify the shape of `data` for each command does not change unexpectedly. These protect consumers from silent breaking changes.
```typescript
it('agents list --json contract', () => {
const output = JSON.parse(stdout);
expect(output).toHaveProperty('success', true);
expect(output).toHaveProperty('data.agents');
expect(output.data.agents[0]).toMatchObject({
key: expect.any(String),
name: expect.any(String),
installed: expect.any(Boolean),
});
});
```
### Test Helpers
Shared utilities in `src/cli/commands/__tests__/helpers/json-test-utils.ts`:
```typescript
function captureJsonOutput(fn: () => Promise<void>): { stdout: string; exitCode: number };
function expectValidJsonSuccess(stdout: string, dataShape?: object): void;
function expectValidJsonError(stdout: string, expectedCode?: string): void;
```
### Estimated Test Count
- ~15-20 tests for output helpers (Layer 1)
- ~2-3 tests per command × ~20 commands = ~40-60 tests (Layer 2)
- ~1 test per command × ~20 commands = ~20 tests (Layer 3)
- Total: ~75-100 test cases

View File

@ -1,299 +0,0 @@
# Spec: Instances CLI & Auth Codes
**Date:** 2026-04-02
**Status:** Draft
**Related specs:**
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
- [Multi-Instance Design](./2026-03-30-multi-instance-design.md)
- [App Spec: Add Workspace Feature](../../OpenACP-App/docs/superpowers/specs/2026-04-02-add-workspace-feature-design.md)
## Overview
Three additions to the OpenACP core to support the Add Workspace feature in the desktop app:
1. **`openacp instances` CLI subcommand** — list and create instances with app-friendly JSON output.
2. **Extend `start --json` output** — include full instance info after startup (wizard or normal start).
3. **Auth code exchange** — one-time codes for secure remote connection, replacing JWT-in-URL.
4. **`GET /api/v1/workspace` endpoint** — lets authenticated clients fetch workspace identity info.
---
## 1. `openacp instances` CLI Subcommand
### Relationship to `openacp status --all`
`openacp status --all` already exists and lists all instances in a table format for terminal users. The new `openacp instances list` command targets **app consumption**: its JSON output uses a different schema (`directory` = parent of `.openacp` root, `root` = `.openacp` path) compared to `status --all --json` which returns runtime fields (`channels`, `runMode`, `pid`). Human-readable output of `instances list` reuses the same table rendering as `status --all`.
---
### `openacp instances list`
Lists all registered instances with live status.
```
openacp instances list [--json]
```
**Status check per instance:**
1. Read `<root>/openacp.pid` — file missing → `stopped`
2. If PID file exists, check process alive (kill -0) → dead process → `stopped`
3. If process alive, `GET http://localhost:<port>/api/v1/system/health` → confirm alive → `running`
**JSON output (`--json`):**
```json
[
{
"id": "main",
"name": "Main",
"directory": "/Users/user",
"root": "/Users/user/.openacp",
"status": "running",
"port": 21420
},
{
"id": "my-project",
"name": "My Project",
"directory": "/Users/user/my-project",
"root": "/Users/user/my-project/.openacp",
"status": "stopped",
"port": null
}
]
```
All paths are **absolute** — no `~/` prefix. `directory` = `path.dirname(root)` (the human-facing project folder, not the `.openacp` subdirectory itself).
**Human-readable output (no `--json`):** Same table format as `openacp status --all`. Can share rendering logic.
---
### `openacp instances create`
Creates or registers a new instance at a given directory, non-interactively.
```
openacp instances create
--dir <path> Target directory — system appends /.openacp internally (user-facing convention from multi-instance spec)
[--from <path>] Clone from this existing instance directory (same convention: parent dir, not /.openacp)
[--name <name>] Instance name (default: openacp-<N>)
[--agent <agentName>] Set default agent in config
[--no-interactive] Skip setup wizard entirely
[--json] Print resulting instance info as JSON to stdout
```
**Flow:**
```
→ Resolve --dir to absolute path (expand ~/, resolve symlinks)
→ Check <dir>/.openacp already exists?
→ Yes + already in registry:
→ Error: "Instance already exists at <dir> (id: <id>)"
→ Exit 1
→ Yes + not in registry:
→ Read instanceName from <dir>/.openacp/config.json
→ Register entry in ~/.openacp/instances.json
→ Skip creation, go to output step
→ No .openacp yet:
→ --from <fromPath> provided:
→ Validate <fromPath>/.openacp/config.json exists (error if not found)
→ Clone using existing copy logic (from multi-instance spec)
→ Register new instance in ~/.openacp/instances.json
→ --no-interactive (no --from):
→ Create <dir>/.openacp/ directory structure
→ Write minimal config.json: { instanceName: <name>, runMode: "daemon" }
→ Write agents.json with default agent if --agent provided
→ Register in ~/.openacp/instances.json
→ Output step:
→ --json: print instance info JSON to stdout, exit 0
→ No --json: print "Instance created: <name> at <dir>", exit 0
```
**JSON output (`--json`):**
```json
{
"id": "my-project",
"name": "My Project",
"directory": "/Users/user/my-project",
"root": "/Users/user/my-project/.openacp",
"status": "stopped",
"port": null
}
```
---
## 2. Extend `start --json` and Onboarding Output
### Current `start --json` Output
`openacp start --json` (and the default command when starting) already outputs:
```json
{ "success": true, "data": { "pid": 1234, "instanceId": "main", "dir": "/Users/user/.openacp" } }
```
`dir` here is the `.openacp` root path.
### Required Change
Extend the `data` payload to include `name` and `directory` (the parent folder, i.e., the human-facing project folder):
```json
{
"success": true,
"data": {
"pid": 1234,
"instanceId": "main",
"name": "Main",
"directory": "/Users/user",
"dir": "/Users/user/.openacp",
"port": 21420
}
}
```
`dir` is kept for backward compatibility. `directory` is `path.dirname(dir)`.
### Onboarding Wizard with `--json`
When `openacp` (or `openacp start`) is run with `--json` and no config exists:
1. The setup wizard runs normally (interactive terminal prompts — `--json` controls output format, not interactivity).
2. After wizard completes and server starts, the extended `start --json` output is emitted.
The app reads this JSON from sidecar stdout to capture the newly created instance's `id` immediately after setup completes.
---
## 3. Auth Code Exchange
### Motivation
The current `openacp remote` spec embeds the JWT directly in the URL (`?token=eyJ...`). Tokens in URLs can be logged by proxies, cached by browsers, and exposed in QR codes. Replacing the JWT with a short-lived one-time code means the actual token is never exposed in a URL.
### New Endpoints
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| `POST` | `/api/v1/auth/codes` | Secret token only | Generate one-time code |
| `POST` | `/api/v1/auth/exchange` | None (code is credential) | Exchange code for JWT |
---
### `POST /api/v1/auth/codes`
Only callable with secret token auth.
**Request body:**
```json
{
"role": "admin",
"name": "remote-14h30-31-03-2026",
"expire": "24h",
"scopes": ["sessions:read"]
}
```
Same fields as `POST /api/v1/auth/tokens` — the code carries the intended token parameters.
**Response:**
```json
{
"code": "abc123xyz",
"expiresAt": "2026-04-02T14:35:00Z"
}
```
**Storage:** In-memory Map `code → { tokenParams, expiresAt, used: false }`. Codes expire after 5 minutes. Cleanup on exchange or expiry.
---
### `POST /api/v1/auth/exchange`
No authentication required — the code is the credential.
**Request body:**
```json
{ "code": "abc123xyz" }
```
**Flow:**
```
→ Look up code in store
→ Not found: 401 "Invalid code"
→ Found but expired: 401 "Code expired"
→ Found but already used: 401 "Code already used"
→ Mark code as used (single-use, prevent replay)
→ Call internal token generation with stored tokenParams
→ Return same response as POST /api/v1/auth/tokens
```
**Response:**
```json
{
"accessToken": "eyJ...",
"tokenId": "tok_abc123",
"expiresAt": "2026-04-03T14:30:00Z",
"refreshDeadline": "2026-04-09T14:30:00Z"
}
```
---
### `openacp remote` — Updated Link Format
```
openacp remote
→ POST /api/v1/auth/codes (secret token) → code "abc123xyz"
→ Generate links:
openacp://connect?host=<tunnel>&code=abc123xyz
https://<tunnel>?code=abc123xyz
http://localhost:<port>?code=abc123xyz
```
The `token=` query param in all link formats is replaced by `code=`. The auth spec's existing link formats are updated accordingly.
---
## 4. `GET /api/v1/workspace`
Returns identity information about the current workspace/instance. Used by the app after connecting to a remote workspace to retrieve the instance `id` and display info.
**Auth:** Any valid auth (secret token or JWT — no specific scope required beyond authentication).
**Response:**
```json
{
"id": "main",
"name": "Main",
"directory": "/Users/user",
"version": "2026.401.1"
}
```
`directory` is `path.dirname(instanceRoot)` — the parent of the `.openacp` folder, i.e., the human-facing project folder.
`directory` is the server-side filesystem path. For remote workspaces, it is meaningful for display only — connection routing uses `host`, not `directory`.
---
## Files to Add / Modify
### New Files (core)
- `src/cli/commands/instances.ts` — `instances list` and `instances create` subcommands
- `src/plugins/api-server/routes/workspace.ts` — `GET /api/v1/workspace` route
- `src/plugins/api-server/auth/code-store.ts` — in-memory code store (TTL + single-use)
- `src/plugins/api-server/routes/auth-codes.ts` — `POST /api/v1/auth/codes` and `POST /api/v1/auth/exchange` routes
### Modified Files (core)
- `src/cli.ts` — register `instances` subcommand in instance-aware command map
- `src/cli/commands/index.ts` — export `cmdInstances`
- `src/cli/commands/start.ts` — extend `--json` output with `name`, `directory`, `port`
- `src/cli/commands/default.ts` — extend `--json` output (startup after wizard) with same fields
- `src/plugins/api-server/routes/auth.ts` — register new code exchange routes
- `src/plugins/api-server/server.ts` — register workspace route
### Modified Files (app)
See companion spec: [App Spec: Add Workspace Feature](../../OpenACP-App/docs/superpowers/specs/2026-04-02-add-workspace-feature-design.md)

View File

@ -1,325 +0,0 @@
# Menu & Command Dispatch Fix
**Date:** 2026-04-02
**Status:** Draft
**Scope:** Fix broken menu buttons, fix slash commands dispatching to generic core handlers, add button-driven New Session flow
## Problem
The main menu shows 10 buttons. When pressed, the `m:` callback handler dispatches them through `CommandRegistry` (core, generic handlers) or does nothing (`callback` type). This causes:
1. **3 buttons completely broken**: Settings (`callback` type → `break`), Update (placeholder text), Doctor (placeholder text)
2. **3 buttons with degraded UX**: Sessions (loses cleanup buttons, status emoji), Agents (loses pagination, install buttons), Help (generic text instead of rich formatted)
3. **1 button unnecessarily slow**: New Session delegates everything to AI when most steps could use buttons
4. **1 button unreliable**: Restart uses `setTimeout` from callback context
5. **Slash commands have the same problems**: `/agents`, `/sessions`, `/doctor`, `/update`, `/help`, `/restart` all go through core generic handlers, missing Telegram-specific rich UI
6. **1 orphaned callback**: `m:topics` (Refresh button in sessions list) has no handler
Buttons that work correctly: Status, Integrate, and all inner buttons (cleanup, agent install, settings toggle/select, switch, permissions, TTS).
## Design
### Principle
Two layers of command handling already exist:
- **Core handlers** in `CommandRegistry` — platform-agnostic, return `CommandResponse`
- **Telegram handlers** — rich UI with inline keyboards, pagination, progress updates
The problem is that the `m:` menu handler and the slash command dispatcher both route to core handlers exclusively. The fix: register Telegram adapter overrides in `CommandRegistry` so both paths (menu button + slash command) get rich UI.
### Part 1: Telegram Command Overrides via Intercept Map
`CommandRegistry` supports adapter-scoped overrides, but override handlers receive `CommandArgs` — not grammY `Context`. The Telegram handlers (`handleAgents`, `handleDoctor`, etc.) need grammY `Context` for inline keyboards, message editing, and rich UI.
Instead of bridging `CommandArgs` → `Context`, use an intercept map: a lookup table that maps command names to Telegram handler functions. Both the slash command dispatcher and the `m:` menu handler check this map before falling through to `CommandRegistry`.
Commands intercepted:
| Command | Telegram handler | What it does |
|---------|-----------------|-------------|
| `/agents` | `handleAgents(ctx, core)` | Paginated list + install buttons |
| `/sessions` | `handleTopics(ctx, core)` | Status emoji + cleanup buttons + refresh |
| `/doctor` | `handleDoctor(ctx)` | Run diagnostics + show report + fix buttons |
| `/update` | `handleUpdate(ctx, core)` | Version check + download + restart |
| `/restart` | `handleRestart(ctx, core)` | Send message, wait for delivery, then restart |
| `/help` | `handleHelp(ctx)` | Rich formatted help with sections |
Implementation:
```typescript
// Shared intercept map — used by both slash command handler and m: menu handler
const TELEGRAM_OVERRIDES: Record<string, (ctx: Context, core: OpenACPCore) => Promise<void>> = {
agents: (ctx, core) => handleAgents(ctx, core),
sessions: (ctx, core) => handleTopics(ctx, core),
doctor: (ctx, _core) => handleDoctor(ctx),
update: (ctx, core) => handleUpdate(ctx, core),
restart: (ctx, core) => handleRestart(ctx, core),
help: (ctx, _core) => handleHelp(ctx),
}
```
#### Slash command dispatch change
In the `bot.on("message:text")` handler at adapter.ts:322, check the intercept map before `registry.execute()`:
```typescript
// Before: always calls registry.execute()
// After: check intercept map first
const override = TELEGRAM_OVERRIDES[commandName]
if (override) {
await override(ctx, core)
return // don't fall through to registry.execute()
}
const response = await registry.execute(text, { ... })
```
#### Menu `m:` handler change for `command` type
In the `m:` handler's `command` case in `commands/index.ts`, check the intercept map before `registry.execute()`:
```typescript
case 'command': {
const cmdName = item.action.command.replace(/^\//, '').split(' ')[0]
const override = TELEGRAM_OVERRIDES[cmdName]
if (override) {
await override(ctx, core)
break
}
// Fallback: dispatch through CommandRegistry (for commands without overrides)
const response = await registry.execute(item.action.command, { ... })
// ... render response
break
}
```
The intercept map is defined once and shared between both dispatch paths. Core handlers remain as fallback for non-Telegram channels.
### Part 2: Fix `callback` Type in `m:` Handler
The `m:` handler has `case 'callback': break;` which silently does nothing. This breaks the Settings button (`s:settings` callbackData).
The issue: grammY callback routing already matched `m:core:settings` → the broad `m:` handler consumed it. The `s:settings` callback data is never re-dispatched to `setupSettingsCallbacks`.
Fix: handle known callback data directly in the `callback` case. grammY does not support re-dispatching callback data, so we must call handlers directly.
```typescript
case 'callback': {
const cbData = item.action.callbackData
if (cbData === 's:settings') {
await handleSettings(ctx, core)
} else if (cbData.startsWith('ns:')) {
// New Session flow — call showAgentPicker directly
await showAgentPicker(ctx, core, chatId)
}
// Future callback types can be added here
break
}
```
This handles the two known `callback` actions: Settings (`s:settings`) and New Session (`ns:start`). Plugins adding new `callback` menu items would need to extend this case — but that's a rare scenario. A more general solution (callback registry) can be added later if needed.
### Part 3: New Session Button Flow
Replace the current `delegate` action (sends everything to AI) with a multi-step button flow. AI is only involved when the user needs to type a custom workspace path.
#### Flow
```
[🆕 New Session] (callback: ns:start)
↓
📋 Select agent (inline buttons)
[claude-code] [gemini]
[codex] [goose]
↓ user taps agent
📁 Select workspace (inline buttons)
[~/project-a] ← from recent session history
[~/project-b] ← from recent session history
[📁 Custom path...] ← only this goes to AI
↓
If recent workspace selected:
→ createSessionDirect(agent, workspace) — no AI needed
If "Custom path..." selected:
→ delegate to AI: "User wants session with agent X, ask for workspace path"
```
#### Callback prefix: `ns:`
| Callback data | Action |
|--------------|--------|
| `ns:start` | Show agent picker |
| `ns:agent:{agentKey}` | Show workspace picker for this agent |
| `ns:ws:{id}` | Create session directly (workspace resolved from cache) |
| `ns:custom:{agentKey}` | Delegate to AI for workspace input |
#### Callback data size constraint
Telegram limits callback_data to 64 bytes. Workspace paths can easily exceed this (e.g. `ns:ws:claude-code:/Users/lucas/some-long-path` = 50+ chars). The adapter already has a compression mechanism (`toCallbackData`/`fromCallbackData` with `callbackCache` Map) but it only handles the `c/` prefix.
For `ns:ws:` callbacks, use a workspace cache instead of embedding the path:
```typescript
// Store workspace in a short-lived cache keyed by numeric ID
const workspaceCache = new Map<number, { agentKey: string; workspace: string }>()
let nextWsId = 0
// When building workspace picker buttons:
const id = nextWsId++
workspaceCache.set(id, { agentKey, workspace })
kb.text(shortLabel, `ns:ws:${id}`) // always short callback data
// When handling ns:ws callback:
const entry = workspaceCache.get(id)
if (!entry) { /* expired — show picker again */ }
```
This keeps callback data under 20 bytes regardless of path length.
#### Agent picker
Shows installed agents as inline buttons (max 2 per row). Source: `core.agentCatalog.getAvailable().filter(i => i.installed)`.
If only 1 agent installed → skip agent picker, go directly to workspace picker.
#### Workspace picker
Recent workspaces extracted from session records:
```typescript
const records = core.sessionManager.listRecords()
const workspaces = [...new Set(records.map(r => r.workingDir))]
.slice(0, 5) // max 5 recent workspaces
```
Each workspace shown as a button. Plus "📁 Custom path..." at the bottom.
If no recent workspaces → use config `workspace.baseDir` as the only option + Custom.
#### Registration
New function `setupNewSessionCallbacks(bot, core, chatId)` in `commands/new-session.ts`, called from `setupAllCallbacks()` before the broad `m:` handler.
### Part 4: Fix `m:topics` Refresh Button
The sessions list (`handleTopics`) creates a "Refresh" button with callback `m:topics`. This reaches the broad `m:` handler which looks up `menuRegistry.getItem("topics")` → undefined → nothing happens.
Fix: add explicit handling in the `m:` handler for `m:topics`:
```typescript
// In the broad m: handler, before menuRegistry lookup
if (itemId === 'topics') {
await handleTopics(ctx, core)
return
}
```
Alternatively, register `m:topics` as a specific callback handler in `setupSessionCallbacks()` (before the broad handler), which is cleaner.
### Part 5: Core Menu Items Update
Changes to `src/core/menu/core-items.ts`:
| Item | Current action | New action | Reason |
|------|---------------|------------|--------|
| New Session | `delegate` | `callback: ns:start` | Button flow instead of AI |
| Restart | `command: /restart` | `command: /restart` | No change — override handles rich UI |
| Update | `command: /update` | `command: /update` | No change — override handles rich UI |
All other items keep their current action type — the adapter overrides handle the rich UI transparently.
## Files Changed
| File | Change | ~LOC |
|------|--------|------|
| `src/plugins/telegram/adapter.ts` | Add `TELEGRAM_OVERRIDES` map, intercept in slash command handler | +20 |
| `src/plugins/telegram/commands/index.ts` | Fix `callback` case, intercept in `m:` handler `command` case, add `m:topics` handling | +30 |
| `src/plugins/telegram/commands/new-session.ts` | Add `setupNewSessionCallbacks()` with `ns:` prefix handlers | +80 |
| `src/core/menu/core-items.ts` | Change New Session action to `callback: ns:start` | ~2 |
| `src/plugins/telegram/commands/session.ts` | Add `m:topics` specific callback (before broad handler) | ~5 |
No files deleted. No core type changes. No breaking changes.
## Complete Flow Diagrams
### Flow 1: User taps "🆕 New Session" menu button
```
User taps [🆕 New Session]
→ callback_data = "m:core:new"
→ broad m: handler → menuRegistry.getItem("core:new")
→ action.type === 'callback', callbackData: 'ns:start'
→ case 'callback': cbData starts with 'ns:' → call setupNewSessionCallbacks handler directly
→ shows agent picker buttons (edit existing message)
→ user taps [claude-code] → ns:agent:claude-code
→ ns: handler shows workspace picker: [~/project-a] [~/project-b] [📁 Custom...]
→ user taps [~/project-a] → ns:ws:42
→ ns: handler resolves workspace from cache → createSessionDirect(ctx, core, chatId, "claude-code", "~/project-a")
→ ✅ Session created with topic
```
Note: The callback_data `m:core:new` is consumed by the broad `m:` handler. Inside `case 'callback'`, the handler must call the `ns:` logic directly — it cannot re-dispatch `ns:start` as a new callback because grammY doesn't support that. Implementation: extract the agent picker logic into a standalone function `showAgentPicker(ctx, core, chatId)` and call it from both the `m:` handler's callback case and the `ns:start` callback handler.
### Flow 2: User taps "🤖 Agents" menu button
```
User taps [🤖 Agents]
→ callback_data = "m:core:agents"
→ broad m: handler → action.type === 'command', command: '/agents'
→ intercept map check: TELEGRAM_OVERRIDES['agents'] exists
→ calls handleAgents(ctx, core)
→ shows paginated agent list with install buttons
```
### Flow 3: User types "/doctor" as slash command
```
User types "/doctor"
→ bot.on("message:text") → commandName = "doctor"
→ intercept map check: TELEGRAM_OVERRIDES['doctor'] exists
→ calls handleDoctor(ctx)
→ shows "Running diagnostics..." → edits message with report + fix buttons
→ (registry.execute() never called)
```
### Flow 4: User taps "⚙️ Settings" menu button
```
User taps [⚙️ Settings]
→ callback_data = "m:core:settings"
→ broad m: handler → action.type === 'callback', callbackData: 's:settings'
→ case 'callback': cbData === 's:settings' → handleSettings(ctx, core)
→ shows settings keyboard with toggle/select buttons
```
### Flow 5: User taps "Refresh" in sessions list
```
User taps [Refresh]
→ callback_data = "m:topics"
→ setupSessionCallbacks handler (registered before broad m: handler)
→ handleTopics(ctx, core)
→ refreshed sessions list with cleanup buttons
```
## Edge Cases
| Case | Behavior |
|------|----------|
| Only 1 agent installed | New Session skips agent picker, goes to workspace picker |
| No recent workspaces | Shows config baseDir + Custom only |
| No agents installed | New Session shows "No agents installed. Use /install" |
| Intercept handler throws | Caught by existing try/catch in slash command handler and `m:` handler |
| User taps old menu button (before update) | `m:core:new` with old `delegate` action — still works via fallback in `m:` handler |
| Workspace path is very long | Workspace stored in cache with numeric ID — callback data always under 20 bytes |
| Workspace cache entry expired (user waited too long) | Show agent picker again with message "Session expired, please try again" |
| Agent key not found after selection | `createSessionDirect` error handling shows error message |
## Testing
1. **Menu button dispatch**: Test each of 10 menu buttons produces correct response (not generic text)
2. **Slash command dispatch**: Test `/agents`, `/sessions`, `/doctor`, `/update`, `/restart`, `/help` produce rich responses
3. **New Session flow**: Test full flow: start → agent picker → workspace picker → session created
4. **New Session single agent**: Test auto-skip when only 1 agent installed
5. **New Session custom workspace**: Test delegation to AI when "Custom" selected
6. **Settings button**: Test `m:core:settings` → settings keyboard appears
7. **Refresh button**: Test `m:topics` → sessions list refreshed
8. **Intercept map**: Test that intercepted commands skip `registry.execute()`, non-intercepted commands still fall through to core handlers

View File

@ -1,324 +0,0 @@
# OpenACP Managed Tunnel — Design Spec
**Date:** 2026-04-02
**Status:** Draft
## Problem
The current Cloudflare tunnel provider uses unauthenticated quick tunnels
(`cloudflared tunnel --url http://localhost:<port>`), which are rate-limited by
Cloudflare and produce random `*.trycloudflare.com` URLs. Users have no stable
URL and can be throttled without warning.
## Solution
Introduce an `openacp` tunnel provider that provisions named Cloudflare tunnels
via an OpenACP-owned Cloudflare Worker. Users get stable subdomains under
`tunnel.openacp.ai`, no login required, and no rate limits from unauthenticated
quick tunnels. The Worker becomes the new default tunnel provider shipped with
OpenACP.
---
## Architecture
```
[OpenACP CLI]
│
├─ POST /tunnel/create (shared API key, IP rate-limited)
│
[Cloudflare Worker — tunnel-worker.openacp.ai]
│
├─ Cloudflare API: create named tunnel + DNS record
├─ KV: store { tunnelId, dnsName, lastPing } with TTL
└─ Returns: { tunnelId, token, publicUrl }
│
[OpenACP CLI]
└─ cloudflared tunnel run --token <token>
Traffic: localhost → cloudflared → CF network → abc123.tunnel.openacp.ai
[Heartbeat — every 10 min]
└─ POST /tunnel/:id/ping → Worker resets KV TTL to 24h
[Cron — every 10 min]
└─ Worker scans KV, deletes tunnels with lastPing > 24h ago
[On stop]
└─ DELETE /tunnel/:id → Worker deletes DNS record + tunnel via CF API
```
Two deliverables:
- `openacp-tunnel-worker/` — new Cloudflare Worker project (TypeScript + Hono)
- `OpenACP/src/plugins/tunnel/providers/openacp.ts` — new `TunnelProvider` implementation
---
## Cloudflare Worker
### Project Structure
```
openacp-tunnel-worker/
src/
index.ts — Hono app, route registration
routes/
create.ts — POST /tunnel/create
ping.ts — POST /tunnel/:id/ping
destroy.ts — DELETE /tunnel/:id
lib/
cloudflare-api.ts — Cloudflare REST API calls (create tunnel, DNS, delete)
rate-limit.ts — IP rate limiting via KV
subdomain.ts — Random 8-char hex subdomain generator
cron.ts — Scheduled cleanup handler
wrangler.toml
```
### Endpoints
| Method | Path | Auth | Description |
|----------|---------------------|-------------|-------------------------------------|
| `POST` | `/tunnel/create` | Shared key | Provision new ephemeral tunnel |
| `POST` | `/tunnel/:id/ping` | Shared key | Reset TTL (heartbeat) |
| `DELETE` | `/tunnel/:id` | Shared key | Delete tunnel immediately |
| `GET` | `/health` | None | Health check |
**Authentication:** `Authorization: Bearer <OPENACP_API_KEY>` header on all
protected endpoints. Key is an environment secret in `wrangler.toml`.
### POST /tunnel/create — Response
```json
{
"tunnelId": "cf-uuid-...",
"publicUrl": "https://abc123.tunnel.openacp.ai",
"token": "eyJ..."
}
```
### KV Data Model
**Namespace:** `TUNNELS`
**Key:** `tunnel:<tunnelId>`
```json
{
"tunnelId": "cf-uuid-...",
"dnsName": "abc123.tunnel.openacp.ai",
"createdAt": 1743580800,
"lastPing": 1743584400
}
```
TTL is managed manually via `lastPing`. The cron handler deletes any entry
where `lastPing` is more than 24 hours ago, then calls the Cloudflare API to
delete the tunnel and its DNS record.
### IP Rate Limiting
**Key:** `ratelimit:<ip>`
**Value:** request count for the current 1-hour window
**Limit:** 5 tunnel creates per IP per hour
Enforced on `POST /tunnel/create` only.
### Subdomain Generation
Generate a random 8-character lowercase hex string. Before creating the DNS
record, verify the subdomain is not already in use in KV. Retry up to 3 times
on collision (statistically negligible).
### Cron Schedule
Runs every 10 minutes. Scans all `tunnel:*` keys in KV. For each entry where
`now - lastPing > 86400s` (24h):
1. Call CF API: delete DNS record
2. Call CF API: delete tunnel
3. Delete KV entry
### Environment Variables (wrangler.toml secrets)
| Variable | Description |
|-----------------------|--------------------------------------------|
| `CF_API_TOKEN` | Cloudflare API token with Tunnel + DNS permissions |
| `CF_ACCOUNT_ID` | Cloudflare account ID |
| `CF_ZONE_ID` | Zone ID for `openacp.ai` |
| `OPENACP_API_KEY` | Shared secret checked on all requests |
---
## OpenACP Core — `OpenACPTunnelProvider`
### New File
`src/plugins/tunnel/providers/openacp.ts`
Implements the existing `TunnelProvider` interface unchanged.
### Constructor
```ts
class OpenACPTunnelProvider implements TunnelProvider {
constructor(
options: Record<string, unknown>,
binDir: string,
storage: PluginStorage,
)
}
```
`options` may carry override values for `workerUrl` and `apiKey` (for testing).
Default values are constants baked into the binary:
```ts
const DEFAULT_WORKER_URL = 'https://tunnel-worker.openacp.ai'
const DEFAULT_API_KEY = '<hardcoded — rotatable via CLI release>'
```
### Persisted State
State is stored in the tunnel plugin's `ctx.storage` under the key
`'openacp-tunnels'`, as a `Record<string, TunnelState>` keyed by port number
(string form, since JSON keys are strings):
```ts
interface TunnelState {
tunnelId: string
token: string
publicUrl: string
}
// Example value in storage:
// {
// "3100": { tunnelId: "cf-...", token: "eyJ...", publicUrl: "https://abc.tunnel.openacp.ai" },
// "5173": { tunnelId: "cf-...", token: "eyJ...", publicUrl: "https://xyz.tunnel.openacp.ai" }
// }
```
### start(port) Flow
```
1. Load all = storage.get('openacp-tunnels') ?? {}
2. If all[port] exists:
a. POST /tunnel/<tunnelId>/ping
b. If 200 OK → reuse: token = all[port].token, publicUrl = all[port].publicUrl
c. If error (404/network) → delete all[port], proceed to step 3
3. POST /tunnel/create → { tunnelId, token, publicUrl }
a. all[port] = { tunnelId, token, publicUrl }
b. storage.set('openacp-tunnels', all)
4. spawn cloudflared tunnel run --token <token>
(publicUrl is already known from Worker response — no stdout parsing needed.
If process exits within 10s, treat as failure and throw.)
5. Start heartbeat: setInterval(() => pingWorker(tunnelId), 10 * 60 * 1000)
6. Return publicUrl
```
### stop(force?) Flow
```
1. clearInterval(heartbeat)
2. Kill cloudflared process (SIGTERM → SIGKILL after 5s, or SIGKILL immediately if force)
3. DELETE /tunnel/<tunnelId> (fire-and-forget, log error if fails)
4. Load all = storage.get('openacp-tunnels') ?? {}
delete all[port]
storage.set('openacp-tunnels', all)
```
### Crash / Unexpected Exit (onExit)
When cloudflared exits after establishment:
- Do NOT call DELETE (tunnel is still valid on CF)
- Do NOT modify storage (token/tunnelId remain valid)
- Clear heartbeat interval
- Invoke registered `onExit` callback → `TunnelRegistry` handles retry with
exponential backoff (existing behavior)
- On retry, `start(port)` finds the saved state, pings worker (still alive),
and reuses the token → same public URL after reconnect
### Existing TunnelRegistry Changes
**`tunnel-registry.ts` — `createProvider()`:** Add one case:
```ts
case 'openacp':
return new OpenACPTunnelProvider(this.providerOptions, this.binDir ?? '', this.storage)
```
`TunnelRegistry` receives a `storage: PluginStorage` constructor argument
(required — `TunnelService` always passes `ctx.storage` down). If provider is
`openacp` and `storage` is absent, `createProvider()` must throw with a clear
error rather than failing silently at runtime.
**`tunnel-service.ts` — `TunnelService` constructor:** Accept and forward
`storage` to `TunnelRegistry`.
### Tunnel Plugin Changes
**`plugins/tunnel/index.ts`:**
1. Add `'storage:read', 'storage:write'` to `permissions` array.
2. Pass `ctx.storage` to `TunnelService` constructor.
3. Update both `install()` and `configure()` provider selection lists to include
`openacp` as the first (default) option:
```
openacp — OpenACP Managed (recommended, no account needed)
cloudflare — Cloudflare quick tunnel
ngrok — ngrok (requires auth token)
bore — bore (self-hostable)
tailscale — Tailscale Funnel
```
4. Default provider in `install()` when migrating from legacy config: keep
existing value to avoid disrupting current users.
---
## Error Handling & Fallback
| Scenario | Behavior |
|----------|----------|
| Worker unreachable on `create` | Log error, throw — `TunnelRegistry` retries with backoff |
| Worker returns 429 (IP rate limit) | Same as above — retry backoff |
| `cloudflared` binary missing | `OpenACPTunnelProvider` calls `ensureCloudflared()` as fallback (reuses existing install logic) |
| `cloudflared` exits unexpectedly | Clear heartbeat, fire `onExit` → registry retries; on retry, saved state is reused if still alive |
| Worker unreachable on `ping` | Log warning, do not throw — tunnel continues running |
| Worker unreachable on `DELETE` | Log warning, continue — cron will cleanup after TTL |
| Saved token rejected by cloudflared | `start()` receives error → delete state entry → create new tunnel |
---
## Backward Compatibility
- Existing users with `provider: 'cloudflare'` in their config are unaffected.
`CloudflareTunnelProvider` is unchanged.
- `openacp` is only the default for **new installs** going through the
interactive `install()` wizard. Existing installs keep their current provider.
- No config migrations needed.
---
## Project Layout (final)
```
openacp-workspace/
OpenACP/ ← core changes
src/plugins/tunnel/
providers/openacp.ts ← NEW provider
tunnel-registry.ts ← add 'openacp' case + storage param
tunnel-service.ts ← forward storage param
index.ts ← permissions + storage + install options
openacp-tunnel-worker/ ← NEW Cloudflare Worker project
src/
index.ts
routes/create.ts, ping.ts, destroy.ts
lib/cloudflare-api.ts, rate-limit.ts, subdomain.ts
cron.ts
wrangler.toml
```
---
## Out of Scope
- User accounts or per-user quotas (shared API key + IP rate limit is sufficient for v1)
- Custom domains per user
- Tunnel analytics or usage dashboard
- Migration of existing `cloudflare` users to `openacp`

View File

@ -1,127 +0,0 @@
# Plugins API Design
## Overview
Add a `/api/v1/plugins` route group to the `api-server` plugin to expose plugin management
capabilities to the OpenACP-App UI. Enables listing installed plugins, fetching the marketplace,
and managing plugin state (enable/disable/uninstall) with hot-reload via `LifecycleManager`.
## New Endpoints
### GET /plugins
List all installed plugins from `PluginRegistry`, enriched with live runtime state from
`LifecycleManager`.
**Response:**
```ts
{
plugins: Array<{
name: string // e.g. "@openacp/telegram"
version: string
description?: string
source: 'builtin' | 'npm' | 'local'
enabled: boolean // from PluginRegistry
loaded: boolean // currently in lifecycleManager.loadedPlugins
failed: boolean // in lifecycleManager.failedPlugins
essential: boolean // see "Field Resolution" below
hasConfigure: boolean // see "Field Resolution" below
}>
}
```
**Field Resolution for `essential` and `hasConfigure`:**
These fields come from the plugin definition (`OpenACPPlugin`), not the registry. Resolution order:
1. **Loaded plugins**: definition is in `lifecycleManager.loadOrder` → read directly.
2. **Failed plugins**: definition is still in `lifecycleManager.loadOrder` (added before boot fails) → read directly.
3. **Disabled builtin plugins**: look up by name in `corePlugins` array.
4. **Disabled npm plugins not loaded**: definition is unavailable → default `essential: false`, `hasConfigure: false`.
### GET /plugins/marketplace
Proxy to `RegistryClient.getRegistry()`. Cached per `RegistryClient` TTL (1 minute).
Each plugin entry includes an `installed` boolean derived from `PluginRegistry`.
**Response:**
```ts
{
plugins: Array<RegistryPlugin & { installed: boolean }>
categories: Array<{ id: string; name: string; icon: string }>
}
```
Returns 503 with `{ error: "Marketplace unavailable" }` if registry fetch fails and no cache exists.
### POST /plugins/:name/enable
Enable a plugin: sets `enabled = true` in `PluginRegistry`, then hot-loads the plugin.
**Loading logic by source:**
- `builtin`: plugin definition is in `corePlugins` — call `lifecycleManager.boot([plugin])` directly.
- `npm` / `local`: dynamically import the module via `importFromDir(name, pluginsDir)`, then call
`lifecycleManager.boot([plugin])`. If import fails, return 500 with message "Plugin module could
not be loaded. Try restarting the server."
**Responses:**
- **404** if plugin not in registry
- No-op if plugin is already loaded (idempotent, still returns 200)
- **500** if `boot()` fails (plugin enters `failed` state) or import fails
### POST /plugins/:name/disable
Disable a plugin: calls `lifecycleManager.unloadPlugin(name)`, then sets `enabled = false`
in `PluginRegistry`.
- **404** if plugin not in registry
- **409** if plugin `essential: true` — refuse with message "Essential plugins cannot be disabled"
- No-op if plugin is already unloaded (still sets `enabled = false`, returns 200)
### DELETE /plugins/:name
Uninstall a plugin: calls `lifecycleManager.unloadPlugin(name)`, removes from `PluginRegistry`,
saves registry.
- **400** if `source === 'builtin'` — refuse with message "Builtin plugins cannot be uninstalled. Use disable instead."
- **404** if plugin not in registry
- Does NOT remove npm package from disk (matches CLI behavior — user can re-enable by re-registering)
## RouteDeps Changes
`RouteDeps` in `routes/types.ts` needs one new optional field:
```ts
lifecycleManager?: LifecycleManager
```
Populated when registering the plugins route in `api-server/index.ts`.
Note: `settingsManager` is NOT needed here — plugin settings are managed by the plugins themselves,
not by plugin management endpoints.
## Authorization
All plugin routes require auth + `system:admin` scope (same as restart endpoint).
## Instance Context
The `lifecycleManager` is scoped to the running instance's `instanceRoot`. Plugin operations
always affect the connected instance only.
## Restart vs Hot-reload
| Action | Restart needed? | Method |
|-----------------------------|-----------------|--------------------------------------------------|
| Install npm plugin | Yes | CLI command shown in app, app shows restart cmd |
| Enable builtin plugin | No | `lifecycleManager.boot()` from `corePlugins` |
| Enable npm plugin | No (best effort)| `importFromDir()` + `lifecycleManager.boot()` |
| Disable plugin | No | `lifecycleManager.unloadPlugin()` |
| Uninstall plugin | No | `lifecycleManager.unloadPlugin()` |
| Configure plugin (settings) | Yes | CLI command shown in app, app shows restart cmd |
## File Location
`src/plugins/api-server/routes/plugins.ts`
Registered in `src/plugins/api-server/index.ts` under prefix `/plugins` with auth enabled.

View File

@ -1,45 +0,0 @@
# Design: Convert Legacy ACP modes/models to configOptions
**Date:** 2026-04-03
**Status:** Implemented
## Problem
Gemini CLI returns `modes` and `models` fields in its `newSession` ACP response (old protocol format):
```json
{
"sessionId": "...",
"modes": { "currentModeId": "code", "availableModes": [...] },
"models": { "currentModelId": "gemini-2.5-pro", "availableModels": [...] }
}
```
OpenACP's session factory only reads the new `configOptions[]` format. As a result, `/model` and `/mode` commands fail with "This agent does not support switching models/modes" because `session.configOptions` remains empty.
## Root Cause
`session-factory.ts` propagates ACP state from `agentInstance.initialSessionResponse` but only handles `resp.configOptions` — ignoring the legacy `modes`/`models` fields that Gemini CLI sends.
## Fix
In `session-factory.ts`, when `configOptions` is absent, build equivalent `ConfigOption[]` objects from the legacy `modes` and `models` fields. The new format takes precedence: if an agent sends `configOptions`, it is used as-is. Only fall back to conversion when `configOptions` is missing.
```typescript
} else {
// Convert legacy modes/models fields (old ACP format) to configOptions
const legacyOptions: ConfigOption[] = [];
if (resp.modes) { /* map to ConfigOption with category: 'mode' */ }
if (resp.models) { /* map to ConfigOption with category: 'model' */ }
if (legacyOptions.length > 0) session.setInitialConfigOptions(legacyOptions);
}
```
## Files Changed
- `src/core/sessions/session-factory.ts` — added legacy conversion logic and type imports
- `src/core/agents/agent-instance.ts` — removed stray `console.log` debug statement
## Scope
Only affects initial session creation. Resumed sessions hydrate from cached `acpState.configOptions` which was already in the new format. Live `config_option_update` events from the agent continue to override as before.

View File

@ -1,392 +0,0 @@
# Multi-Adapter Session Routing Design
**Date**: 2026-04-03
**Status**: Draft
**Approach**: Per-session multi-bridge fan-out (Approach 2)
## Problem
Sessions are currently bound 1:1 to a single adapter via `session.channelId`. A session created on Telegram can only be interacted with from Telegram. SSE/API cannot observe or interact with Telegram sessions, and vice versa.
Adapters are just UI layers — ways to input and receive responses. Sessions and conversation history are stored centrally in core. The 1:1 binding is an artificial limitation.
## Goals
1. Sessions are global — not owned by a single adapter
2. Any adapter can attach to any session via explicit action
3. SSE/API can observe and interact with all sessions (full history available)
4. Telegram/Discord only see sessions they're attached to
5. Response routing: source adapter receives the response
6. SSE always receives all events from all attached sessions
7. System/automation can send prompts and specify which adapter receives the response
## Non-Goals
- Cross-adapter context coherence (accepted limitation — each adapter shows only its own turns)
- Auto-attaching adapters to sessions (must be explicit action)
- Real-time sync of conversation history across adapters (Telegram stores its own, SSE reads from core store)
## Architecture
### Core Concepts
**Primary adapter (`channelId`)**: The adapter that created the session. Serves as default `responseAdapterId` for system-sent prompts. Stored in `SessionRecord`.
**Attached adapters (`attachedAdapters[]`)**: All adapters connected to a session, including the primary. Each has its own `SessionBridge` and thread/topic.
**Turn routing context (`TurnContext`)**: Metadata sealed at prompt dequeue time, carried by every event emitted during that turn. Determines where responses are routed.
```ts
interface TurnContext {
turnId: string; // unique per prompt execution
sourceAdapterId: string; // "telegram" | "sse" | "discord" | "system"
responseAdapterId: string | null; // override target; null = silent (no UI render)
}
```
**Effective response target**: `turnContext.responseAdapterId ?? turnContext.sourceAdapterId`. When `null`, no adapter renders the response (silent/internal prompt).
### Session Data Model Changes
```ts
// Before
class Session {
channelId: string; // single adapter
threadId: string; // single thread
}
// After
class Session {
channelId: string; // primary adapter (creator)
attachedAdapters: string[]; // all adapters connected to this session
threadIds: Map<string, string>; // adapterId → threadId (per-adapter)
activeTurnContext: TurnContext | null; // set on prompt dequeue, cleared on turn end
}
```
### SessionRecord (Persistence) Changes
```ts
// Before
interface SessionRecord {
channelId: string;
platform: { topicId?: number; threadId?: string };
}
// After
interface SessionRecord {
channelId: string; // primary adapter (unchanged)
attachedAdapters: string[]; // persisted adapter list
platforms: { // per-adapter platform data
telegram?: { topicId: number };
discord?: { threadId: string };
sse?: { threadId: string };
// ...extensible per adapter
};
}
```
**Migration**: Old records with `platform: { topicId: 123 }` auto-migrate on load to `platforms: { telegram: { topicId: 123 } }`. `channelId` determines which adapter key to use for migration.
### Multi-Bridge Architecture
Each session maintains multiple `SessionBridge` instances — one per attached adapter:
```
Session
├── bridges: Map<adapterId, SessionBridge>
│ ├── "telegram" → SessionBridge (Telegram adapter)
│ ├── "discord" → SessionBridge (Discord adapter)
│ └── "sse" → SessionBridge (SSE adapter)
└── activeTurnContext: TurnContext
```
**Bridge forwarding logic** (per event):
```ts
class SessionBridge {
adapterId: string;
shouldForward(event: AgentEvent, turnContext: TurnContext): boolean {
// System events → all attached adapters
if (isSystemEvent(event)) return true;
// Silent turn → no adapter renders
const target = turnContext.responseAdapterId;
if (target === null) return false;
// Turn events → only target adapter
const effectiveTarget = target ?? turnContext.sourceAdapterId;
return this.adapterId === effectiveTarget;
}
}
```
**SSE bridge**: Same logic as above. SSE receives events because it's attached to the session. No special-casing — SSE is just another adapter that happens to attach to many/all sessions.
### Event Classification
**Turn events** (routed to response adapter only):
- `text`, `thought`, `tool_call`, `tool_update`, `plan`, `usage`, `error`, `attachment`, `resource`, `resource_link`, `user_replay`
**System events** (broadcast to all attached adapters):
- `session_end`, `mode_change`, `config_update`, `model_update`, `system_message`
### Message Input Flow
```
User types on Telegram
→ TelegramAdapter.handleMessage({ channelId: "telegram", threadId: "123", text: "..." })
→ core.handleMessage(message)
→ session = findByThread("telegram", "123") // lookup via threadIds map
→ session.enqueuePrompt(text, attachments, { sourceAdapterId: "telegram" })
→ PromptQueue dequeues
→ TurnContext sealed: { turnId: "abc", sourceAdapterId: "telegram", responseAdapterId: undefined }
→ Agent processes, emits events
→ Each event tagged with TurnContext
→ Telegram bridge: shouldForward() → true (effectiveTarget == "telegram")
→ SSE bridge: shouldForward() → false (effectiveTarget != "sse")
BUT SSE is attached and receives system events
→ Discord bridge: shouldForward() → false
```
**SSE sending to a Telegram session:**
```
SSE client sends to session X
→ POST /sessions/:id/messages { text: "..." }
→ session.enqueuePrompt(text, null, { sourceAdapterId: "sse" })
→ TurnContext: { sourceAdapterId: "sse", responseAdapterId: undefined }
→ Agent responds
→ Telegram bridge: shouldForward() → false (target is "sse")
→ SSE bridge: shouldForward() → true
```
### Silent System Prompts
For internal operations (auto-naming, health checks, etc.) where the response should not render on any UI:
```ts
session.enqueuePrompt("Name this session in 5 words", null, {
sourceAdapterId: "system",
responseAdapterId: null, // silent — no adapter renders
});
// TurnContext: { sourceAdapterId: "system", responseAdapterId: null }
// All bridges: shouldForward() → false (target is null)
// SSE observer connection (if subscribed): receives event tagged silent for debug visibility
```
The response is consumed programmatically by the caller (e.g., session auto-naming extracts the name from the agent's response).
### Permission Handling
**Request flow**: Permission request is a system event → broadcast to ALL attached adapters.
```
Agent requests permission
→ Session emits permission_request
→ ALL bridges forward (system event)
→ Telegram shows inline keyboard
→ SSE shows permission UI
→ Discord shows buttons
```
**Resolution flow**: First adapter to respond wins.
```
SSE user clicks "Allow"
→ resolvePermission(requestId, "allow")
→ PermissionGate resolves (removes from pending map)
→ Core broadcasts "permission:resolved" event to all bridges
→ Telegram updates inline keyboard → "✅ Resolved by SSE"
→ Discord updates buttons → "✅ Resolved by SSE"
→ Late resolution attempts → requestId not in map → silent no-op
```
### Attach / Detach API
**Attach adapter to session:**
```
POST /sessions/:sessionId/attach
Body: { adapterId: "telegram" }
Flow:
1. Validate session exists, adapter is running
2. adapter.createSessionThread(sessionId, sessionName) → threadId
3. session.threadIds.set("telegram", threadId)
4. session.attachedAdapters.push("telegram")
5. Create new SessionBridge for Telegram
6. bridge.connect()
7. Update SessionRecord (persist attachedAdapters + platforms)
8. Send "Session attached" message to new adapter's thread
```
**Detach adapter from session:**
```
POST /sessions/:sessionId/detach
Body: { adapterId: "discord" }
Flow:
1. Send "Session detached" message to Discord thread
2. Bridge disconnect + remove from session.bridges
3. Remove from session.attachedAdapters
4. Remove session.threadIds["discord"]
5. Clean up pending permission UIs on that adapter
6. Update SessionRecord
7. Cannot detach primary adapter (channelId) — error if attempted
```
### Session Creation Flow Changes
```ts
// Before: createSession({ channelId, ... })
// After: createSession({ channelId, ... })
// channelId becomes primary adapter
// attachedAdapters initialized to [channelId]
// threadIds initialized with primary adapter's thread
async createSession(params) {
const session = await sessionFactory.create(params);
session.attachedAdapters = [params.channelId];
session.threadIds = new Map();
const adapter = this.adapters.get(params.channelId);
if (params.createThread && adapter) {
const threadId = await adapter.createSessionThread(session.id, name);
session.threadIds.set(params.channelId, threadId);
}
// Create bridge for primary adapter
if (adapter) {
const bridge = this.createBridge(session, adapter);
bridge.connect();
}
// Persist with new format
await this.sessionManager.patchRecord(session.id, {
attachedAdapters: session.attachedAdapters,
platforms: this.buildPlatforms(session),
});
return session;
}
```
### Agent Switch Changes
When agent switches, reconnect bridges for ALL attached adapters (not just primary):
```ts
async switchAgent(sessionId, toAgent) {
// ... existing agent switch logic ...
// Reconnect ALL bridges
for (const adapterId of session.attachedAdapters) {
const adapter = this.adapters.get(adapterId);
if (adapter) {
const bridge = this.createBridge(session, adapter);
bridge.connect();
}
}
}
```
### Lazy Resume Changes
When a session is resumed (triggered by any attached adapter), create bridges for ALL attached adapters:
```ts
async getOrResume(channelId, threadId) {
// ... existing resume logic ...
if (resumedSession) {
// Create bridges for ALL attached adapters, not just the triggering one
for (const adapterId of resumedSession.attachedAdapters) {
const adapter = this.adapters.get(adapterId);
if (adapter) {
const bridge = this.createBridge(resumedSession, adapter);
bridge.connect();
}
}
}
return resumedSession;
}
```
### Notification Routing
**Turn-related notifications** (triggered by a specific turn):
- Route to `turnContext.responseAdapterId ?? turnContext.sourceAdapterId`
**System-wide notifications** (not tied to any turn):
- Route to `session.channelId` (primary adapter)
**SSE**: Receives all notifications if attached (same bridge logic — notifications are system events).
### PromptQueue Changes
```ts
// Before
interface QueuedPrompt {
text: string;
attachments?: Attachment[];
}
// After
interface QueuedPrompt {
text: string;
attachments?: Attachment[];
routing: {
sourceAdapterId: string;
responseAdapterId?: string | null; // null = silent, undefined = use sourceAdapterId
};
}
```
### Conversation History Enhancement
Context plugin stores `sourceAdapterId` per message entry:
```ts
interface ConversationEntry {
role: "user" | "assistant";
content: string;
timestamp: string;
sourceAdapterId?: string; // NEW — which adapter sent this message
}
```
SSE/API dashboard can use this to display message provenance.
## Backward Compatibility
1. **SessionRecord migration**: Old `platform: { topicId }` → new `platforms: { telegram: { topicId } }`. Auto-migrate on load using `channelId` to determine adapter.
2. **Missing `attachedAdapters`**: Old records without this field → default to `[channelId]`.
3. **Missing `platforms`**: Fall back to reading old `platform` field → migrate to new format.
4. **`session.threadId` compatibility**: Maintain a getter `get threadId()` that returns `threadIds.get(channelId)` for backward compatibility during migration. Deprecate direct access.
5. **PromptQueue routing**: Old prompts without `routing` field → default `{ sourceAdapterId: session.channelId }`.
## Summary of Changes by Component
| Component | Change |
|---|---|
| `Session` | Add `attachedAdapters`, `threadIds` Map, `activeTurnContext` |
| `SessionRecord` | Add `attachedAdapters`, rename `platform` → `platforms` (per-adapter) |
| `SessionStore` | Auto-migrate old records on load |
| `SessionBridge` | Add `adapterId`, `shouldForward(event, turnContext)` logic |
| `PromptQueue` | Add `routing` metadata to queued prompts |
| `OpenACPCore` | Multi-bridge creation, attach/detach API, agent switch reconnect all |
| `SessionFactory` | Resume creates bridges for all attached adapters |
| `PermissionGate` | Idempotent resolution (no-op if already resolved) |
| `API Server` | New endpoints: attach, detach, send-to-session |
| `SSE Adapter` | Per-session bridge (same as other adapters), attaches to desired sessions |
| `EventBus` | New event: `permission:resolved` |
| `Context Plugin` | Add `sourceAdapterId` to conversation entries |

View File

@ -1,368 +0,0 @@
# Security Hardening Design
**Date:** 2026-04-03
**Issues:** #69, #70, #74, #75
**Approach:** Hybrid — Core boundaries + Middleware policies
## Overview
OpenACP has multiple critical security vulnerabilities across agent filesystem access, process execution, agent installation, plugin system, and tunnel subsystem. This design addresses all 15 remaining vulnerabilities in a single branch using a hybrid approach: core enforces hard boundaries (cannot be bypassed), security plugin handles configurable policies.
### Current State (Vulnerabilities)
| Area | Critical | High | Medium |
|------|----------|------|--------|
| Agent filesystem/process (#69) | 2 | 3 | 1 |
| Agent installation (#70) | 2 | 2 | 2 |
| Plugin system (#74) | 1 | 0 | 0 |
| Tunnel system (#75) | 1 | 3 | 0 |
| **Total** | **5** | **8** | **3** |
Already fixed (not in scope): shell injection (#74), plugin crash handling (#74), execSync blocking (#74), timing attack (#75), process leak (#75).
## Section 1: Workspace Sandbox (Core)
### PathGuard Module
**File:** `src/core/security/path-guard.ts`
PathGuard validates all file operations against workspace boundaries. It receives `cwd` (immutable from session), `allowedPaths` (from config), and `.openacpignore` patterns.
**Interface:**
```typescript
interface PathGuardOptions {
cwd: string;
allowedPaths: string[];
ignorePatterns: string[]; // from .openacpignore + defaults
}
class PathGuard {
constructor(options: PathGuardOptions);
validatePath(targetPath: string, operation: 'read' | 'write'): { allowed: boolean; reason: string };
}
```
**Validation logic:**
1. Normalize path via `path.resolve()`, resolve symlinks via `fs.realpathSync()`
2. Check path starts with `cwd` or any entry in `allowedPaths` — if not → reject
3. Check path against `.openacpignore` patterns — if match → reject
4. Return `{ allowed: true }`
### `.openacpignore`
Located at `{cwd}/.openacpignore`. Syntax identical to `.gitignore` (use `ignore` npm package).
**Built-in default patterns** (always applied, even without file):
```
.env*
*.key
*.pem
.ssh/
.aws/
.openacp/
**/credentials*
**/secrets*
**/*.secret
```
User patterns in `.openacpignore` are merged on top of defaults. Agent **cannot** write to `.openacpignore` itself (hardcoded in PathGuard).
### Core Enforcement Points
- `agent-instance.ts:566-579` → `readTextFile()`: call `pathGuard.validatePath(path, 'read')` before `readTextFileWithRange()`
- `agent-instance.ts:581-594` → `writeTextFile()`: call `pathGuard.validatePath(path, 'write')` before `fs.writeFile`
- `agent-instance.ts:699-703` → attachment file reading: call `pathGuard.validatePath(path, 'read')` before `fs.promises.readFile()`
- `terminal-manager.ts:40-123` → `createTerminal()`: validate `cwd` param is within allowed boundaries
- `read-text-file.ts:7-17` → `readTextFileWithRange()`: add PathGuard check (this is the underlying utility used by readTextFile)
- On reject → return error to agent (no crash, agent sees "file restricted" message)
### API/SSE Path Redaction
Agent output streamed via SSE or returned via API should not leak absolute file paths outside workspace:
- `viewer-routes.ts:40-63` → `/api/file/:id` and `/api/diff/:id`: replace absolute `filePath` with workspace-relative path (strip `cwd` prefix)
- `workspace.ts:14-19` → `/workspace` endpoint: already requires `sessions:read` scope, acceptable to expose workspace directory to authenticated clients
- SSE `agent:event` payloads: no additional filtering needed (tool outputs may reference paths, but the sandbox prevents actual access)
### Config
```typescript
workspace: {
security: {
allowedPaths: string[] // default: [] — cwd only
envWhitelist: string[] // default: see Section 2
}
}
```
## Section 2: Environment Variable Filtering (Core)
### EnvFilter Module
**File:** `src/core/security/env-filter.ts`
```typescript
function filterEnv(
processEnv: Record<string, string>,
agentEnv?: Record<string, string>,
whitelist?: string[]
): Record<string, string>;
```
**Logic:**
1. Start with empty object
2. Copy only whitelisted keys from `process.env` (supports glob patterns like `LC_*`)
3. Merge `agentEnv` on top (agent-defined vars from agent config)
4. Return filtered env
**Default whitelist:**
```typescript
const DEFAULT_ENV_WHITELIST = [
"PATH", "HOME", "SHELL", "LANG", "LC_*", "TERM", "USER", "LOGNAME",
"TMPDIR", "XDG_*", "NODE_ENV", "EDITOR"
];
```
Admin extends via `workspace.security.envWhitelist` in config.
### Enforcement Points
- `agent-instance.ts:197` — replace `{ ...process.env, ...agentDef.env }` with `filterEnv(process.env, agentDef.env)`
- `terminal-manager.ts:78` — replace `{ ...process.env, ...env }` with `filterEnv(process.env, env)`
- Tunnel provider spawn calls (ngrok.ts, bore.ts, cloudflare.ts, tailscale.ts) — these inherit parent env implicitly via `spawn()` without explicit `env` option. Add `env: filterEnv(process.env, providerEnv)` to each spawn call.
### Backward Compatibility
Default whitelist covers all vars needed for normal agent operation. If an agent needs a specific var, admin adds it to config.
## Section 3: Auto-Approve Fix + Permission Hardening (Core)
### Fix Auto-Approve Bypass
**Remove** the description-based auto-approve in `session-bridge.ts:365-396`.
Current `PermissionRequest` type (`core/types.ts:44-48`) only has `id`, `description`, `options` — no `toolId` field. Two options:
**Option chosen:** Instead of adding `toolId` to the ACP protocol type, simplify by removing auto-approve entirely. The bypass was originally added for convenience but creates a security hole. Permission requests should always go through the normal approval flow (user approval or bypass mode for headless API).
```typescript
// BEFORE (vulnerable):
if (request.description.toLowerCase().includes("openacp")) { ... }
// AFTER (secure):
// Remove the entire description-based auto-approve block.
// Auto-approve is only available via explicit bypass mode (which requires sessions:dangerous scope).
```
This is the safest approach — no string matching, no toolId dependency, no way for agents to self-approve.
### Headless API Bypass Protection
- `POST /sessions/:id/dangerous` → require new scope `sessions:dangerous` (separate from `sessions:write`)
- Log warning when bypass is enabled
### Workspace Path Sanitization
Fix `resolveWorkspace()` in `config.ts`:
```typescript
resolveWorkspace(input?: string): string {
if (!input) return expandAndCreate(this.config.workspace.baseDir);
// Named workspace only — no absolute paths, no traversal
const name = input.replace(/[^a-zA-Z0-9_-]/g, '');
if (name !== input) throw new Error(`Invalid workspace name: "${input}"`);
return expandAndCreate(path.join(this.config.workspace.baseDir, name));
}
```
Reject absolute paths, `~` paths, and `..` traversal. Only allow simple named workspaces.
## Section 4: Agent Installation Security (Core)
### Checksum Verification
Registry adds `sha256` field per binary target. New download flow:
1. Download with size limit
2. Verify SHA-256 hash
3. Validate tar contents (list before extract)
4. Extract
```typescript
const buffer = await downloadWithSizeLimit(archiveUrl, MAX_DOWNLOAD_SIZE);
if (expectedHash) {
const actualHash = crypto.createHash('sha256').update(buffer).digest('hex');
if (actualHash !== expectedHash) {
throw new Error(`Integrity check failed: expected ${expectedHash}, got ${actualHash}`);
}
}
```
If registry has no hash → log warning, allow install (backward compat) but display warning to user.
### Download Size Limit
- `MAX_DOWNLOAD_SIZE = 500 * 1024 * 1024` (500MB)
- `readResponseWithProgress()` aborts when `received > MAX_DOWNLOAD_SIZE`
### Validate-Before-Extract (Fix TOCTOU)
Use `tar -tf` to list archive contents before extraction:
- Reject entries containing `..`
- Reject absolute paths
- Reject symlinks pointing outside destDir
- Only proceed with `tar -xzf` if all entries pass
### Uninstall Path Validation
```typescript
const agentsDir = path.resolve(expandHome("~/.openacp/agents"));
const realPath = path.resolve(agent.binaryPath);
if (!realPath.startsWith(agentsDir + path.sep)) {
throw new Error(`Refusing to delete path outside agents directory: ${realPath}`);
}
```
### File Permissions
- `agents.json` and registry cache → write with `mode: 0o600`
- `mkdirSync` for agents dir → `mode: 0o700`
### Shared with `install-binary.ts` (Tunnel Binaries)
Same patterns apply: size limit, tar content validation before extract, checksum when available.
## Section 5: Plugin System Hardening
### npm `--ignore-scripts`
Add flag to all npm install calls:
- `plugin-installer.ts:67` → add `--ignore-scripts`
- `wizard.ts:304` → add `--ignore-scripts` to setup wizard npm install
- `wizard.ts:357` → add `--ignore-scripts` to setup wizard npm install
```typescript
await execAsync(`npm install ${packageName} --prefix "${dir}" --save --ignore-scripts`, {
timeout: 60000,
});
```
Prevents all postinstall/preinstall RCE across all npm install paths.
### Plugin Scope Restriction (Configurable)
```typescript
// Config
plugins: {
trustedScopes: string[] // default: ["@openacp"]
}
```
- If `trustedScopes` is non-empty → only allow packages from those scopes
- If empty → allow any (backward compat)
- Warn user when installing packages outside trusted scope
### Plugin Permission Audit Logging
Log each plugin access to `ctx.core` (configManager, sessionManager, adapters). Security plugin can subscribe to `plugin:coreAccess` events for monitoring.
## Section 6: Tunnel Security
### Auth Default On
- Tunnel viewer routes → `auth: true` by default
- On first tunnel start → auto-generate random token: `crypto.randomBytes(32).toString('hex')`
- Token stored in tunnel config, displayed to user at tunnel creation
- User must explicit set `auth.enabled: false` for public access
### XSS Sanitization
Fix `file-viewer.ts:158-164`. Current code already loads DOMPurify from CDN (`cdn.jsdelivr.net/npm/dompurify@3.2.4`) but has two issues:
1. Falls back to **unsanitized** `innerHTML` if DOMPurify fails to load
2. External CDN dependency can be compromised or unavailable
**Fix:**
- Remove CDN dependency for DOMPurify
- Implement inline `sanitizeHtml()` function directly in the template string (this is a server-rendered template, not a separate JS file)
- The sanitizer strips `<script>` tags, `on*` event attributes, `javascript:` URIs
- Allows safe tags: `p`, `h1`-`h6`, `ul`, `ol`, `li`, `a`, `code`, `pre`, `blockquote`, `em`, `strong`, `img`
- Fallback when `marked` is unavailable already escapes HTML correctly (line 162-163) — no change needed there
### Credentials via Environment Variables
Replace CLI arguments with env vars:
| Provider | Before | After |
|----------|--------|-------|
| ngrok | `--authtoken TOKEN` | `env: { NGROK_AUTHTOKEN: token }` |
| bore | `--secret SECRET` | `env: { BORE_SECRET: secret }` |
| openacp | `--token TOKEN` | `env: { CLOUDFLARE_TUNNEL_TOKEN: token }` |
Process args no longer contain secrets → `ps aux` safe.
## Section 7: Testing Strategy
### New Test Files
| File | Covers |
|------|--------|
| `src/core/security/__tests__/path-guard.test.ts` | PathGuard: cwd boundary, allowedPaths, `.openacpignore`, symlink escape, `..` traversal, default deny patterns |
| `src/core/security/__tests__/env-filter.test.ts` | EnvFilter: whitelist, glob patterns, agent env merge, secrets not leaked |
| `src/core/agents/__tests__/agent-installer-security.test.ts` | Checksum verify, size limit abort, tar content validation, uninstall path validation |
| `src/plugins/tunnel/__tests__/tunnel-security.test.ts` | Auth default on, XSS sanitization, credentials in env not args |
### Updated Test Files
| File | Updates |
|------|---------|
| `src/core/sessions/__tests__/session-bridge-autoapprove.test.ts` | Verify description-based bypass no longer works, only toolId whitelist |
| `src/core/plugin/__tests__/plugin-installer.test.ts` | Verify `--ignore-scripts` flag present, trusted scope rejection |
### Key Test Scenarios
**PathGuard:**
- Allow read file within cwd
- Reject read file outside cwd (`/etc/passwd`, `~/.ssh/id_rsa`)
- Reject path traversal (`cwd + "/../../../etc/passwd"`)
- Reject symlink pointing outside cwd
- Reject `.openacpignore` matched files (`.env`, `*.key`)
- Allow file in `allowedPaths` config
- Default deny patterns apply even without `.openacpignore` file
- Agent cannot write to `.openacpignore` itself
**EnvFilter:**
- Only whitelisted vars passed through
- Glob patterns work (`LC_*` matches `LC_ALL`)
- `AWS_SECRET_ACCESS_KEY` not leaked
- Agent-defined vars merged correctly
**Auto-approve:**
- Description containing "openacp" NO LONGER auto-approves
- Auto-approve block is fully removed (no string matching, no toolId)
- Only bypass mode (requiring `sessions:dangerous` scope) can skip permissions
**Installer:**
- Mismatched SHA-256 rejects install
- Download > 500MB aborted
- Tar with `../` entries rejected BEFORE extraction
- Uninstall path outside `~/.openacp/agents/` rejected
**Plugin:**
- `npm install` includes `--ignore-scripts` (plugin-installer.ts AND wizard.ts)
- Untrusted scope warns/rejects per config
**API path redaction:**
- `/api/file/:id` returns workspace-relative path, not absolute
- `/api/diff/:id` returns workspace-relative path, not absolute
**Tunnel:**
- Auth enabled by default (viewer routes require token)
- Markdown XSS payloads sanitized
- Credentials passed via env vars, not CLI args

View File

@ -1,130 +0,0 @@
# Session List History — Design
**Date:** 2026-04-03
**Status:** Approved
## Problem
`GET /sessions` API only returns sessions currently live in memory. Sessions that have been
cancelled, finished, or archived are removed from memory and become invisible to the API consumer.
This means the OpenACP App cannot show the user a full session history for browsing or resuming.
## Goal
`GET /sessions` returns all sessions — live and historical — in a single unified response shape.
Historical sessions (from the store) get `null`/`0`/`false` for runtime-only fields.
## Design
### New method: `SessionManager.listAllSessions(channelId?: string): SessionSummary[]`
Single method that merges the store records (all statuses) with live in-memory session data.
```typescript
export interface SessionSummary {
id: string; // maps from SessionRecord.sessionId
agent: string;
status: SessionStatus;
name: string | null;
workspace: string;
channelId: string;
createdAt: string;
lastActiveAt: string | null;
dangerousMode: boolean;
// Runtime fields — populated from live session; null/0/false for historical
queueDepth: number;
promptRunning: boolean;
configOptions?: ConfigOption[];
capabilities: AgentCapabilities | null;
isLive: boolean;
}
```
**Logic:**
1. If store is available: query `listRecords()` as source of truth (all statuses)
2. For each record: look up `getSession(record.sessionId)` to check if live
3. If live: overlay runtime fields (`queueDepth`, `promptRunning`, `configOptions`, `capabilities`,
current `status`)
4. If not live: use record fields, runtime fields default to `0`/`false`/`null`/`undefined`
5. If no store: fallback to `listSessions()` mapped to `SessionSummary` (live-only, no history)
6. Filter by `channelId` if provided
The `isLive` flag lets consumers distinguish sessions that can be interacted with right now vs.
historical records only.
### Route change: `GET /sessions`
```typescript
// Before
const sessions = deps.core.sessionManager.listSessions();
return { sessions: sessions.map(s => ({ ... })) };
// After
const summaries = deps.core.sessionManager.listAllSessions();
return { sessions: summaries.map(s => ({ ... })) };
```
Response shape is the same as today for live sessions. Historical sessions fill runtime fields with
`0`/`false`/`null`. The `isLive` field is added to the response.
### Response shape (unified)
```json
{
"sessions": [
{
"id": "abc123",
"agent": "claude",
"status": "active",
"name": "My Session",
"workspace": "/home/user/project",
"channelId": "telegram",
"createdAt": "2026-04-01T10:00:00Z",
"lastActiveAt": "2026-04-01T11:00:00Z",
"dangerousMode": false,
"queueDepth": 0,
"promptRunning": false,
"configOptions": [],
"capabilities": null,
"isLive": true
},
{
"id": "def456",
"agent": "claude",
"status": "cancelled",
"name": "Old Session",
"workspace": "/home/user/project",
"channelId": "telegram",
"createdAt": "2026-03-30T09:00:00Z",
"lastActiveAt": "2026-03-30T10:00:00Z",
"dangerousMode": false,
"queueDepth": 0,
"promptRunning": false,
"configOptions": undefined,
"capabilities": null,
"isLive": false
}
]
}
```
## Files Changed
- `src/core/sessions/session-manager.ts` — add `SessionSummary` interface + `listAllSessions()` method
- `src/plugins/api-server/routes/sessions.ts` — update `GET /` handler to use `listAllSessions()`
- `src/plugins/api-server/__tests__/routes-sessions.test.ts` — update existing tests + add new cases
## Tests
- Live session → runtime fields populated, `isLive: true`
- Historical session (store only, not in memory) → runtime fields null/0/false, `isLive: false`
- Mixed (some live, some historical) → correct merge, no duplicates
- No store → fallback to live-only, behaves like current behavior
- `channelId` filter applies to both live and historical
## Out of Scope
- No changes to chat commands (`/sessions` in Telegram already uses `listRecords()`)
- No pagination (existing behavior)
- No sort order changes

View File

@ -1,127 +0,0 @@
# Design: File Attachment Support for Prompt Endpoint
**Date:** 2026-04-04
**Based on:** PR #199 (feat/file-upload-api) with security and correctness fixes
## Overview
Extend `POST /sessions/:id/prompt` (REST and SSE routes) to accept an optional `attachments` array alongside the prompt text. Attachments are base64-encoded by the client, decoded on the server, saved via `FileService`, and passed to `session.enqueuePrompt()`.
## Schema (`src/plugins/api-server/schemas/sessions.ts`)
Add `AttachmentInputSchema`:
```typescript
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
'audio/ogg', 'audio/mpeg', 'audio/wav', 'audio/webm', 'audio/mp4',
'video/mp4', 'video/webm',
'application/pdf',
'text/plain',
]);
const AttachmentInputSchema = z.object({
fileName: z
.string()
.min(1)
.max(500)
.refine(
(v) => !v.includes('..') && !v.startsWith('/') && !v.startsWith('~'),
{ message: 'fileName must not contain path traversal sequences' },
),
mimeType: z
.string()
.refine((v) => ALLOWED_MIME_TYPES.has(v), {
message: 'mimeType is not supported',
}),
data: z.string().max(15_000_000), // ~10 MB base64 ≈ 13.3 MB string
});
```
Extend `PromptBodySchema`:
```typescript
export const PromptBodySchema = z.object({
prompt: z.string().min(1).max(100_000),
sourceAdapterId: z.string().optional(),
responseAdapterId: z.string().nullable().optional(),
attachments: z.array(AttachmentInputSchema).max(10).optional(),
});
```
## Shared Helper (`src/plugins/api-server/routes/attachments.ts`)
Extract decode+save logic into a shared utility to avoid duplication between REST and SSE routes:
```typescript
export async function decodeAttachments(
fileService: FileServiceInterface,
sessionId: string,
rawAttachments: AttachmentInput[],
): Promise<Attachment[]>
```
Behavior:
- Decode each `data` field from base64 → `Buffer`
- Call `fileService.saveFile(sessionId, fileName, buffer, mimeType)` for each
- On any failure: clean up already-saved files, rethrow
- Uses `Promise.all()` — all files processed concurrently
## Route Handlers
### REST (`src/plugins/api-server/routes/sessions.ts`)
```typescript
const body = PromptBodySchema.parse(request.body);
const attachments = body.attachments?.length
? await decodeAttachments(deps.core.fileService, sessionId, body.attachments)
: undefined;
await session.enqueuePrompt(body.prompt, attachments, {
sourceAdapterId: body.sourceAdapterId ?? 'api',
responseAdapterId: body.responseAdapterId,
});
```
### SSE (`src/plugins/sse-adapter/routes.ts`)
```typescript
const body = PromptBodySchema.parse(request.body);
const attachments = body.attachments?.length
? await decodeAttachments(deps.core.fileService, sessionId, body.attachments)
: undefined;
await session.enqueuePrompt(body.prompt, attachments, { sourceAdapterId: 'sse' });
```
## Fastify Body Limit (`src/plugins/api-server/server.ts`)
Add `bodyLimit` to `Fastify()` init to support up to 10 × ~15MB attachments:
```typescript
const app = Fastify({
logger: options.logger ?? false,
forceCloseConnections: true,
bodyLimit: 160 * 1024 * 1024, // 160 MB — supports up to 10 × ~15 MB base64 attachments
});
```
## `.gitignore`
Add `**/.DS_Store` to prevent accidental binary file commits.
## Tests (`src/plugins/api-server/__tests__/routes-sessions.test.ts`)
Add `fileService` mock to `createMockDeps()`. New test cases:
1. **Attachment decoded and passed to `enqueuePrompt`** — send valid attachment, assert `saveFile` called, `enqueuePrompt` called with `Attachment[]`, routing args preserved
2. **`saveFile` failure → 500, no partial state leak** — mock `saveFile` to throw, assert cleanup called and response is 500
3. **Too many attachments → 400** — send 11 attachments, assert Zod rejects with 400
4. **Path traversal in `fileName` → 400** — send `../../etc/passwd`, assert 400
5. **Unsupported mimeType → 400** — send `text/html`, assert 400
## What is NOT in scope
- Rate limit per upload endpoint (follow-up)
- Magic byte / content-type verification (follow-up)
- Video/large file streaming (follow-up)

Some files were not shown because too many files have changed in this diff Show More