Compare commits

..

No commits in common. "main" and "security-hardening" have entirely different histories.

224 changed files with 2814 additions and 17595 deletions

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/`

2
.gitignore vendored
View File

@ -1,5 +1,3 @@
.DS_Store
# References (external/third-party code)
references/
node_modules/

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

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).

101
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,34 +34,15 @@ 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>
@ -105,13 +82,6 @@ If you already have Node.js 20+ installed:
```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!
```
---
@ -180,7 +150,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 |
@ -231,59 +201,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 +213,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

View File

@ -472,7 +472,6 @@ openacp integrate <agent> --uninstall
```bash
openacp integrate claude
openacp integrate claude --uninstall
openacp integrate opencode
```
---

View File

@ -79,7 +79,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

@ -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.
@ -30,7 +30,7 @@ Run the integrate command and follow the prompts:
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.
You will be asked which agent to integrate (Claude Code, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). The command installs the necessary hooks so your agent can hand off sessions to OpenACP.
To uninstall later:
@ -56,26 +56,19 @@ The session appears as a new topic in your Telegram group or Discord server. You
- 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`.
- `jq` must be installed on the machine (`brew install jq` on macOS, `apt install jq` on Linux).
---
## 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.
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.
---
## Technical details
Most handoff integrations rely on two shell scripts installed by `openacp integrate`:
Handoff relies 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.

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

@ -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.
---

View File

@ -55,7 +55,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`

Binary file not shown.

Before

Width:  |  Height:  |  Size: 951 KiB

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,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)

View File

@ -1,102 +0,0 @@
# SSE Cross-Adapter Input Visibility
**Date:** 2026-04-04
**Status:** Approved
## Problem
The SSE `/events` stream already receives all agent response events from any adapter (Telegram, Discord, etc.) via the EventBus `agent:event`. However, it does not see the *input* messages that trigger those responses. When a user sends a message from Telegram, the app (SSE client) only sees the AI response — not the original message text, who sent it, or its lifecycle (queued vs actively processing).
## Goals
- SSE receives cross-adapter input messages with text, metadata, and queue lifecycle state
- App can display full conversation history including messages from other adapters
- App can show accurate typing indicators by knowing when processing starts
## Non-Goals
- Input visibility for messages sent by the SSE/API adapter itself (app already knows)
- `done` state — already covered by existing `session_end` / agent event stream
## Design
### New EventBus Events
Two new events added to `EventBusEvents`:
```typescript
"message:queued": {
sessionId: string;
turnId: string; // generated at enqueue time
text: string;
sourceAdapterId: string;
attachments?: Attachment[];
timestamp: string; // ISO — time of enqueue
queueDepth: number; // position in queue at time of enqueue
}
"message:processing": {
sessionId: string;
turnId: string; // same ID as message:queued — allows pairing
sourceAdapterId: string;
timestamp: string; // ISO — time dequeue started
}
```
### turnId Lifecycle
`turnId` is generated at `enqueuePrompt()` time (not at dequeue), stored in the queue item, and passed into `createTurnContext()` when dequeued. This allows `message:queued` and `message:processing` to share the same `turnId` for client-side pairing.
### Filter: Which Adapters Emit
Only adapters that are "external" (have a registered adapter instance) emit these events. The filter: `sourceAdapterId !== 'sse' && sourceAdapterId !== 'api'`. This excludes the app's own messages; only Telegram, Discord, and other platform adapters trigger the events.
### Implementation Flow
```
[Telegram sends message]
→ core.handleMessage()
→ session.enqueuePrompt(text, attachments, { sourceAdapterId: 'telegram' })
→ generates turnId = nanoid()
→ stores { text, routing: { sourceAdapterId, turnId }, ... } in queue
→ core emits EventBus "message:queued" { sessionId, turnId, text, ... }
[Queue processes next item]
→ session.processPrompt()
→ dequeues item with pre-generated turnId
→ session.activeTurnContext = createTurnContext(sourceAdapterId, responseAdapterId, turnId)
→ session.emit("turn_started", activeTurnContext)
[SessionBridge receives turn_started]
→ if sourceAdapterId not in ['sse', 'api']
→ eventBus.emit("message:processing", { sessionId, turnId, sourceAdapterId, ... })
[SSEManager receives both events]
→ broadcasts to all SSE clients filtered by sessionId
```
### File Changes
| File | Change |
|------|--------|
| `src/core/event-bus.ts` | Add `"message:queued"` and `"message:processing"` to `EventBusEvents` |
| `src/core/sessions/prompt-queue.ts` | Add `turnId: string` to queue item type |
| `src/core/sessions/turn-context.ts` | `createTurnContext()` accepts optional `turnId` param; generates if not provided |
| `src/core/sessions/session.ts` | `enqueuePrompt()` generates `turnId`, stores in queue item; `processPrompt()` passes `turnId` to `createTurnContext()`; emits `turn_started` after `activeTurnContext` set |
| `src/core/core.ts` | After `session.enqueuePrompt()` in `handleMessage()`: emit `message:queued` if sourceAdapterId is external |
| `src/core/sessions/session-bridge.ts` | Listen to `turn_started` session event → emit `message:processing` on EventBus |
| `src/plugins/api-server/sse-manager.ts` | Subscribe to `message:queued` + `message:processing`; add both to sessionId-filtered event list |
### Backward Compatibility
- `turnId` in queue item is new; no existing queue items are persisted across restarts (in-memory only)
- `createTurnContext()` signature change is additive (optional param with default)
- New EventBus events are additive — no existing listeners affected
## Testing
- `message:queued` emitted for Telegram/Discord messages but NOT for 'sse'/'api' sources
- `message:processing` emitted when dequeued with matching `turnId`
- Both events filtered by `sessionId` in SSEManager
- `turnId` matches between `message:queued` and `message:processing` for same turn
- Queue depth reflects position at enqueue time

View File

@ -1,212 +0,0 @@
# Config Legacy Removal Design
**Date:** 2026-04-05
**Scope:** OpenACP core + all built-in plugins
## Problem
The config system has evolved through three layers that now coexist awkwardly:
1. **`config.json`** (original) — contains channels, security, speech, tunnel, usage, api sections
2. **Plugin settings files** (`~/.openacp/plugins/<name>/settings.json`) — the intended destination for all plugin config
3. **`plugin-config-migration.ts`** — scaffolding for migrating layer 1 → layer 2, never integrated
This creates several pain points:
- Same env vars (e.g. `OPENACP_TELEGRAM_BOT_TOKEN`) handled in two places: `applyEnvOverrides()` and `applyEnvToPluginSettings()`
- Dual-source fields: some values can exist in either `config.json` or plugin settings, making reads ambiguous
- Every plugin `install()` hook has boilerplate to check `ctx.legacyConfig` and manually migrate old fields
- `config-registry.ts` hardcodes plugin-specific editable fields that belong to the plugins themselves
## Goals
- Single source of truth per field: core fields live in `config.json`, plugin fields live in plugin settings
- Single env override path per field: no duplicate handling
- Plugins self-declare their editable fields instead of relying on a central registry
- Remove unused migration scaffolding and legacy compatibility code
## Non-Goals
- Backward compatibility with old `config.json` format (assumed all users already migrated)
- Changes to the plugin settings file format or SettingsManager API
- Changes to how agents are stored (agents.json is separate)
## Approach: Two-Phase Config First
### Phase 1 — Core Cleanup
#### 1.1 ConfigSchema Cleanup
Remove these sections from `ConfigSchema` in `config.ts`:
| Section | Moves to plugin |
|---------|----------------|
| `channels` (telegram, discord, slack, etc.) | `@openacp/telegram`, `@openacp/discord`, `@openacp/slack` |
| `security` | `@openacp/security` |
| `speech` | `@openacp/speech` |
| `tunnel` | `@openacp/tunnel` |
| `usage` | `@openacp/usage` |
| `api` | `@openacp/api-server` |
**ConfigSchema after cleanup** retains only core fields:
```
instanceName, defaultAgent, workspace, logging,
runMode, autoStart, sessionStore, integrations,
agentSwitch, outputMode
```
Note: `agents` field is already empty after the `migrate-agents-to-store` migration (agents live in `agents.json`). Remove it from schema too.
#### 1.2 Config Migrations Cleanup
Remove these migrations from `config-migrations.ts` (no longer needed):
- `add-tunnel-section`
- `fix-agent-commands`
- `migrate-agents-to-store`
- `migrate-display-verbosity-to-output-mode`
- `migrate-tunnel-provider-to-openacp`
**Keep:** `add-instance-name` (still relevant for new users who have never run setup)
If no migrations remain besides `add-instance-name`, simplify `config-migrations.ts` accordingly.
#### 1.3 Delete Unused Files
- Delete `src/core/config/plugin-config-migration.ts` (unused scaffolding, never integrated)
#### 1.4 Env Vars Cleanup
**`applyEnvOverrides()` — core fields only:**
| Env Var | Config Path |
|---------|------------|
| `OPENACP_DEFAULT_AGENT` | `defaultAgent` |
| `OPENACP_RUN_MODE` | `runMode` |
| `OPENACP_LOG_LEVEL` | `logging.level` |
| `OPENACP_LOG_DIR` | `logging.logDir` |
| `OPENACP_DEBUG` | `logging.level = "debug"` (if no `OPENACP_LOG_LEVEL`) |
Remove from `applyEnvOverrides()`: all channel tokens, `OPENACP_TUNNEL_*`, `OPENACP_API_PORT`, `OPENACP_SPEECH_*`.
**`applyEnvToPluginSettings()` — plugin fields only (unchanged mapping):**
| Env Var | Plugin | Settings Key |
|---------|--------|-------------|
| `OPENACP_TELEGRAM_BOT_TOKEN` | `@openacp/telegram` | `botToken` |
| `OPENACP_TELEGRAM_CHAT_ID` | `@openacp/telegram` | `chatId` (Number) |
| `OPENACP_DISCORD_BOT_TOKEN` | `@openacp/discord` | `botToken` |
| `OPENACP_DISCORD_GUILD_ID` | `@openacp/discord` | `guildId` |
| `OPENACP_SLACK_BOT_TOKEN` | `@openacp/slack` | `botToken` |
| `OPENACP_SLACK_APP_TOKEN` | `@openacp/slack` | `appToken` |
| `OPENACP_SLACK_SIGNING_SECRET` | `@openacp/slack` | `signingSecret` |
| `OPENACP_TUNNEL_ENABLED` | `@openacp/tunnel` | `enabled` (Boolean) |
| `OPENACP_TUNNEL_PORT` | `@openacp/tunnel` | `port` (Number) |
| `OPENACP_TUNNEL_PROVIDER` | `@openacp/tunnel` | `provider` |
| `OPENACP_API_PORT` | `@openacp/api-server` | `port` (Number) |
| `OPENACP_SPEECH_STT_PROVIDER` | `@openacp/speech` | `sttProvider` |
| `OPENACP_SPEECH_GROQ_API_KEY` | `@openacp/speech` | `groqApiKey` |
Each env var now handled in exactly one place.
#### 1.5 Test Updates (Phase 1)
- Remove test cases for deleted migrations
- Remove assertions for plugin-specific env vars that moved out of `applyEnvOverrides()`
- Do not change test structure or add new test logic
---
### Phase 2 — Plugin API
#### 2.1 Plugin Field Declaration API
Add `registerEditableFields()` to `PluginContext`:
```typescript
interface FieldDef {
key: string; // settings key, e.g. "botToken"
displayName: string; // UI label
type: "toggle" | "select" | "number" | "string";
scope: "safe" | "sensitive";
hotReload?: boolean; // default: false
options?: string[]; // for "select" type only
}
// In PluginContext:
registerEditableFields(fields: FieldDef[]): void;
```
Plugins call this in `setup()`:
```typescript
async setup(ctx) {
ctx.registerEditableFields([
{ key: "botToken", displayName: "Bot Token", type: "string", scope: "sensitive" },
{ key: "chatId", displayName: "Chat ID", type: "number", scope: "safe" },
]);
// ... rest of setup
}
```
The registry stores `Map<pluginName, FieldDef[]>` accessible by the API/config editor.
#### 2.2 config-registry.ts Cleanup
Remove all plugin-mapped field definitions. Keep only core fields:
- `defaultAgent`
- `logging.level`
- `workspace.baseDir`
- `sessionStore.ttlDays`
- `agentSwitch.labelHistory`
- `outputMode` (global default)
Remove the `plugin?: { name, key }` mapping from `ConfigFieldDef` if no core field uses it after cleanup.
#### 2.3 Plugin `install()` Cleanup
Remove `legacyConfig` from `InstallContext`. Update these plugins:
| Plugin | Change |
|--------|--------|
| `@openacp/telegram` | Remove `legacyConfig.channels.telegram` migration branch |
| `@openacp/discord` | Remove `legacyConfig.channels.discord` migration branch |
| `@openacp/slack` | Remove `legacyConfig.channels.slack` migration branch |
| `@openacp/security` | Remove `legacyConfig.security` migration branch |
| `@openacp/speech` | Remove `legacyConfig.speech` migration branch |
| `@openacp/tunnel` | Remove `legacyConfig.tunnel` migration branch |
| `@openacp/usage` | Remove `legacyConfig.usage` migration branch |
| `@openacp/api-server` | Remove `legacyConfig.api` migration branch |
Each plugin's `install()` retains only the interactive setup path.
Add `registerEditableFields()` calls to each plugin's `setup()` based on their `settingsSchema`.
#### 2.4 Test Updates (Phase 2)
- Remove test branches that exercise legacy migration paths in plugin `install()`
- Do not change interactive setup test logic
- Add minimal tests for `registerEditableFields()` registration (that fields appear in registry)
---
## File Impact Summary
### Phase 1
- `src/core/config/config.ts` — remove schema sections, slim down `applyEnvOverrides()`
- `src/core/config/config-migrations.ts` — remove 5 migrations, keep `add-instance-name`
- `src/core/config/plugin-config-migration.ts` — **delete**
- `src/core/config/__tests__/` — trim tests matching removed code
### Phase 2
- `src/core/plugin/plugin-context.ts` — add `registerEditableFields()`
- `src/core/plugin/plugin-context-types.ts` — add `FieldDef` interface, update `PluginContextAPI`
- `src/core/config/config-registry.ts` — remove plugin-mapped fields, keep core only
- `src/packages/plugin-sdk/` — export `FieldDef` type
- `src/plugins/telegram/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/discord/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/slack/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/security/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/speech/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/tunnel/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/usage/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/api-server/index.ts` — cleanup install, add registerEditableFields
- `src/plugins/*/` — test cleanup for legacy branches

View File

@ -1,120 +0,0 @@
# Fix: Onboard Channel Setup Flow
## Problem Summary
The `configureChannels()` flow in `src/core/setup/setup-channels.ts` has three bugs
that cause incorrect behavior during `openacp onboard` (reconfigure mode):
1. **Wrong hook called**: When a channel is NOT yet configured, the code calls
`plugin.configure()` instead of `plugin.install()`, giving the user a
field-by-field edit form instead of the full guided setup wizard.
2. **Discord import broken**: `configureViaPlugin('discord', ...)` tries
`import('discord')`, which always fails silently — no setup flow runs at all.
3. **Discord status detection uses wrong plugin name**: `getChannelStatuses()` reads
settings from `@openacp/adapter-discord`, but the installed package may register
under a different name (e.g. `@openacp/discord-adapter`), causing a configured
adapter to always appear as "not configured".
---
## Root Cause Trace
### Bug 1 — `configureViaPlugin()` always calls `configure()`
```
configureChannels()
├── isConfigured = false → falls through (no prompt)
└── configureViaPlugin() → always calls plugin.configure() ← WRONG
should call plugin.install()
```
The `configure()` hook on the Telegram plugin shows "Change bot token" /
"Change chat ID" as separate fields. The `install()` hook runs the full guided
flow (validate token → detect chat ID → confirm admin). A first-time setup
must use `install()`.
**Fix:** Pass `isConfigured` to `configureViaPlugin()` and branch:
```typescript
// if not yet configured → install (full guided setup)
if (!isConfigured && plugin.install) {
await plugin.install(ctx);
// if already configured and user chose "modify" → configure (edit fields)
} else if (plugin.configure) {
await plugin.configure(ctx);
}
```
---
### Bug 2 — Discord plugin import uses short channel ID
```typescript
// channelId = "discord" (key from CHANNEL_META)
const pluginModule = await import(channelId); // import('discord') → FAIL
```
The CHANNEL_META key `"discord"` is a logical ID, not an npm package name.
**Fix:** Add a mapping from logical channel ID to npm package name, and use
that for dynamic import:
```typescript
const CHANNEL_PACKAGE_MAP: Record<string, string> = {
discord: '@openacp/discord-adapter',
// add other community/official adapters here as they ship
};
const packageName = CHANNEL_PACKAGE_MAP[channelId] ?? channelId;
const pluginModule = await import(packageName);
```
---
### Bug 3 — Discord status detection reads wrong settings key
```typescript
// Hard-coded name that may not match what the plugin registered under
const ps = await settingsManager.loadSettings("@openacp/adapter-discord");
```
Settings are stored under `plugin.name` as declared by the package itself.
If `@openacp/discord-adapter` declares `name: "@openacp/discord"`, the
settings file is at `<data>/@openacp/discord/settings.json`, not
`@openacp/adapter-discord/settings.json`.
**Fix:** Align the status-detection key with the same mapping used for import:
```typescript
} else if (settingsManager && id === "discord") {
const ps = await settingsManager.loadSettings("@openacp/discord-adapter"); // match plugin.name
if (ps.guildId || ps.token) { ... }
}
```
> **Note:** Verify the exact `plugin.name` value from the Discord adapter
> package before applying this fix. The correct name can be confirmed by
> inspecting `node_modules/@openacp/discord-adapter/dist/index.js` after a
> test install.
---
## Files to Change
| File | Changes |
|------|---------|
| `src/core/setup/setup-channels.ts` | Fix `configureViaPlugin()` signature + install/configure branch; fix Discord import; fix Discord status key |
---
## Generalization
The same pattern applies to any future community adapter added to `CHANNEL_META`.
The rule is:
- `CHANNEL_META` key = logical ID for display/routing
- `CHANNEL_PACKAGE_MAP` = logical ID → npm package name (for import)
- `getChannelStatuses()` = logical ID → plugin settings name (must match `plugin.name`)
- `configureViaPlugin()` = call `install()` for first-time, `configure()` for edit
These three mappings must be kept in sync whenever a new adapter is added.

View File

@ -1,246 +0,0 @@
# Telegram Topics UX Improvements
**Date:** 2026-04-05
**Status:** Approved
**Scope:** `src/plugins/telegram/`, `docs/`
## Problem
When a user sets up the Telegram plugin on a group that does not have Topics enabled (or where the bot lacks the "Manage Topics" admin permission), the bot starts silently, does nothing, and gives no feedback — in the Telegram chat or in logs. The user has no idea what went wrong or how to fix it.
Additionally, the codebase and docs use "supergroup" throughout, which is an internal Telegram API type name that does not appear in the Telegram UI. This confuses users who are not familiar with Telegram internals.
## Goals
1. Replace misleading "supergroup" terminology with user-facing language ("group with Topics enabled").
2. During install (`openacp plugin install @openacp/telegram`): warn when Topics are not enabled or bot lacks "Manage Topics" permission, provide actionable instructions, and let the user decide whether to proceed.
3. At runtime startup: if prerequisites are not met, send a clear message to the group's General topic, log the issue, then retry silently in the background every 30 seconds. When prerequisites are met, complete initialization and confirm success.
## Out of Scope
- No changes to session topic lifecycle (create, rename, delete).
- No changes to Slack or other adapters.
- No new commands or UI surfaces.
## Terminology Changes
Replace all user-facing occurrences of "supergroup" with appropriate plain language. Internal API type comparisons (`type === 'supergroup'`) remain unchanged because they reflect the Telegram API value.
| Location | Before | After |
|----------|--------|-------|
| `index.ts` install prompt | "Send a message in your Telegram supergroup" | "Send a message in your Telegram group" |
| `index.ts` manual input label | "Supergroup chat ID (e.g. -1001234567890):" | "Group chat ID (e.g. -1001234567890):" |
| `index.ts` fallback manual label | same | same fix |
| `validators.ts` error message | `"Chat is X, must be a supergroup"` | `"Chat must be a group (not a channel or private chat)"` |
| `topics.ts` comment | `// chatId for supergroups starts with -100` | `// chatId for groups starts with -100` |
| `index.ts` plugin description | `'Telegram adapter with forum topics'` | `'Telegram adapter with Topics support'` |
| `docs/gitbook/platform-setup/telegram.md` | "Supergroup with Topics enabled" | "group with Topics enabled" |
| `docs/gitbook/troubleshooting/telegram-issues.md` | "supergroup" references | "group" / "group with Topics enabled" |
| `docs/gitbook/using-openacp/chat-commands.md` | "forum topic" | "topic" |
| `README.md` | any "supergroup" references | "group with Topics enabled" |
| `CLAUDE.md` | "Forum topics" | "Topics" |
## Install Flow Changes (`index.ts`)
### isForum check
After `validateChatId()` succeeds, check `chatResult.isForum`:
```
if isForum === false:
show warning:
⚠ Topics are not enabled on this group.
OpenACP requires Topics to organize sessions.
To enable Topics:
1. Open your group in Telegram
2. Go to Group Settings → Edit
3. Enable "Topics"
ask: "Topics not enabled. Continue anyway? (You can fix this before starting)"
→ Yes: continue install
→ No: exit setup without saving
```
### can_manage_topics check
After `validateBotAdmin()` succeeds (bot is admin), add a new check: does the bot's admin role include `can_manage_topics`?
Extend `validateBotAdmin()` (or add `validateBotTopicsPermission()`) to check the `can_manage_topics` field on the getChatMember result.
```
if can_manage_topics === false:
show warning:
⚠ Bot does not have "Manage Topics" permission.
To fix:
1. Open Group Settings → Administrators
2. Select the bot
3. Enable "Manage Topics"
ask: "Bot cannot manage topics. Continue anyway?"
→ Yes: continue install
→ No: exit setup without saving
```
Both warnings can appear in the same install run if both issues exist.
## Runtime Startup Changes (`adapter.ts`)
### New: `checkTopicsPrerequisites()`
A new private method on `TelegramAdapter` that runs the following checks via the Telegram API:
1. `getChat(chatId)` → verify `is_forum === true`
2. `getMe()` + `getChatMember(chatId, botId)` → verify `status === 'administrator' | 'creator'`
3. Same getChatMember result → verify `can_manage_topics === true`
Returns `{ ok: true }` or `{ ok: false; issues: string[] }` where `issues` is a list of human-readable problems.
### Modified: `start()` flow
The `start()` method is split into two phases:
**Phase 1 — always runs (early init):**
- Create bot, DraftManager, SkillManager
- Register middleware (chatId filter, rate-limit handler, allowed_updates)
- Register command handlers and callback handlers (topic-independent)
- Start bot polling
- Run `checkTopicsPrerequisites()`
- If ok → run Phase 2 immediately
- If not ok → send setup message to General → start background watcher → return (start() completes)
**Phase 2 — topic-dependent init (runs immediately or via watcher):**
- `ensureTopics()` (with existing retryWithBackoff for transient errors)
- Set `this.notificationTopicId`, `this.assistantTopicId`
- Call `setupMenuCallbacks(...)` with resolved topic IDs (previously called early with undefined IDs — must now be deferred)
- Set up `session:threadReady` and `session:configChanged` event handlers
- Set up routes (`setupRoutes()`)
- Spawn assistant (`assistantManager.spawn(...)`)
- Send welcome message to `assistantTopicId`
- Log "Telegram adapter fully initialized"
**Background watcher loop (only when prerequisites not met):**
- Retry `checkTopicsPrerequisites()` with schedule: 5s, 10s, 30s, then 30s indefinitely
- On each failure: log debug (no spam)
- On success:
- Run Phase 2
- Send success message to General: "✅ OpenACP is ready! System topics have been set up."
- Cancel watcher
**Watcher cleanup:** The watcher must be cancelled if `stop()` is called while it is still running. Add a `_prerequisiteWatcher` field (e.g., a timeout handle or a cancel flag) that `stop()` clears.
### Handling messages while watcher is running
**Regular messages** (non-command text in topics): silently dropped (log warn). No response is sent.
**Commands** (`/new`, `/status`, etc.): respond with a brief message in the same topic/chat:
```
⏳ OpenACP is still setting up. Check the General topic for instructions.
```
This avoids silent confusion when a user types a command before setup completes.
**Callback queries** (button clicks): answered with an empty response to dismiss the spinner; no action taken.
### General topic message format
**On failure (sent once at startup):**
```
⚠️ OpenACP needs setup before it can start.
[for each issue]:
❌ Topics are not enabled on this group.
→ Go to Group Settings → Edit → enable "Topics"
❌ Bot cannot manage topics.
→ In Admin settings, enable "Manage Topics" permission
OpenACP will automatically retry every 30 seconds.
```
**On success (sent after watcher completes initialization):**
```
✅ OpenACP is ready!
System topics have been created. Use the 🤖 Assistant topic to get started.
```
## Validators Changes (`validators.ts`)
### `validateBotAdmin()` (or new `validateBotTopicsPermission()`)
Extend the existing function to also return `canManageTopics: boolean` in the success result:
```typescript
{ ok: true; canManageTopics: boolean }
```
This allows the install flow to check both admin status and topics permission in one pass.
Alternatively, if keeping the functions separate is cleaner: add a new `validateBotTopicsPermission(token, chatId)` function that only checks `can_manage_topics`.
Preference: extend `validateBotAdmin()` to return `canManageTopics` in the success case — avoids a second API call since it uses the same getChatMember result.
## Docs Changes
### `docs/gitbook/platform-setup/telegram.md`
- Replace all "Supergroup" / "supergroup" → "group" or "group with Topics enabled" as appropriate.
- Step 2: Remove the sentence "Telegram converts the group to a Supergroup automatically" — replace with a plain note that enabling Topics upgrades the group internally, which is handled automatically by Telegram.
- Add a "Prerequisites" checklist before Step 1:
1. A Telegram group (any size)
2. Topics enabled (Group Settings → Edit → Topics)
3. Bot added as admin with "Manage Topics" permission
- Step 6 "Expected output": update log lines to match new startup flow; add a note that if prerequisites are not met, OpenACP will send instructions to the group's General topic and retry automatically.
- Step 5 config format: the doc currently shows the old `channels.telegram.*` config path. Add a note clarifying that running `openacp` or `openacp plugin install @openacp/telegram` is the recommended setup method and the config is stored in plugin settings, not main config.
- Troubleshooting section at bottom: update "Chat is not a supergroup" entry to match new terminology and behavior.
### `docs/gitbook/troubleshooting/telegram-issues.md`
- Replace all "supergroup" occurrences with "group" (keep "negative number starting with -100" note unchanged — that is a factual description).
- **Rewrite** the "Topics are not created on startup" section:
- Old: lists manual steps to diagnose.
- New: explain that OpenACP now detects this automatically at startup, sends a message to the group's General topic with exact instructions, and retries every 30 seconds. User just needs to follow the instructions in the group.
- **Add** new entry: "Bot cannot manage topics" — symptoms, cause, and the fix (enable "Manage Topics" in admin settings).
- Update "Not enough rights" entry: remove the "Convert to Supergroup" step; replace with "Enable Topics in Group Settings → Edit → Topics".
### `docs/gitbook/using-openacp/chat-commands.md`
- Replace "forum topic" with "topic" (minor).
### `README.md`
- Update any "supergroup" references to "group with Topics enabled".
### `CLAUDE.md` (project root)
- Update "Forum topics (Telegram)" → "Topics (Telegram)" in the adapter patterns section.
## Error Detection
Detecting "Topics not enabled" from Telegram API errors:
When `createForumTopic` is called on a non-forum group, Telegram returns:
```json
{ "ok": false, "error_code": 400, "description": "Bad Request: method is available for supergroups only" }
```
or
```json
{ "ok": false, "error_code": 400, "description": "Bad Request: TOPIC_DISABLED" }
```
`checkTopicsPrerequisites()` uses `getChat()` to avoid this — it detects the problem before attempting to create topics. So runtime error detection in `ensureTopics()` is only a fallback.
## Files to Change
| File | Change type |
|------|-------------|
| `src/plugins/telegram/index.ts` | Add isForum + can_manage_topics warnings in install(); fix "supergroup" terminology in prompts |
| `src/plugins/telegram/validators.ts` | Extend validateBotAdmin() to return canManageTopics; fix error message terminology |
| `src/plugins/telegram/adapter.ts` | Split start() into Phase 1/2; add checkTopicsPrerequisites(); background watcher; command guard; stop() watcher cleanup |
| `src/plugins/telegram/topics.ts` | Fix comment terminology |
| `docs/gitbook/platform-setup/telegram.md` | Terminology + prerequisites section + updated startup behavior note |
| `docs/gitbook/troubleshooting/telegram-issues.md` | Terminology + rewrite "Topics not created" + add "Bot cannot manage topics" entry |
| `docs/gitbook/using-openacp/chat-commands.md` | Minor terminology ("forum topic" → "topic") |
| `README.md` | Terminology |
| `CLAUDE.md` | Terminology ("Forum topics" → "Topics") |

View File

@ -1,143 +0,0 @@
# Persistent Assistant Session Design
**Date:** 2026-04-06
**Status:** Approved
## Problem
Every time the bot restarts, `AssistantManager.spawn()` always creates a new session. Over time this accumulates many stale assistant session records in `SessionStore` and in the sessions list visible to users. The intended behaviour is: one assistant session per channel, reused across restarts.
## Goals
- One persistent assistant session record per channel (no accumulation of garbage records).
- On bot restart: reuse the existing assistant session ID, start a fresh AgentInstance (no history preserved — intentional).
- Assistant sessions must not appear in session listings (chat commands, REST API, UI).
- Remove the `/clear` command for the assistant (source of confusion; fresh context is already provided on every restart).
## Non-Goals
- Preserving conversation history across restarts (out of scope; fresh context is correct behaviour).
- Resuming assistant AgentInstance state (no ACP state snapshot needed).
---
## Design
### 1. `SessionRecord` — Add `isAssistant` field
**File:** `src/core/types.ts`
Add an optional field to `SessionRecord`:
```typescript
isAssistant?: boolean;
```
This flag is `true` only for assistant sessions. Absent/`false` for all regular sessions. Backward compatible — old records without this field are treated as regular sessions.
### 2. `SessionStore` — Add `findAssistant()` method
**File:** `src/core/sessions/session-store.ts`
Add to `SessionStore` interface:
```typescript
findAssistant(channelId: string): SessionRecord | undefined;
```
Implementation in `JsonFileSessionStore`: iterate records, return first where `record.isAssistant === true && record.channelId === channelId`.
### 3. `AssistantManager` — `getOrSpawn()` replaces `spawn()`
**File:** `src/core/assistant/assistant-manager.ts`
Replace `spawn()` with `getOrSpawn()`. The `AssistantManagerCore` interface gains read access to `sessionStore` (or a `findAssistantSession(channelId)` helper).
**Logic:**
```
getOrSpawn(channelId, threadId):
existing = sessionStore.findAssistant(channelId)
if existing:
session = createSession({ ..., sessionId: existing.sessionId, isAssistant: true })
// overwrite the old record with updated metadata (new agentSessionId, timestamps)
else:
session = createSession({ ..., isAssistant: true })
store pendingSystemPrompt
return session
```
The `Session` constructor must accept an optional `id` override so the existing session ID can be reused.
Remove `respawn()` — no longer needed. The Telegram adapter's welcome message on restart is sufficient; users get a fresh context automatically.
### 4. Persist `isAssistant` in `SessionRecord`
**File:** `src/core/core.ts` (or wherever `AssistantManagerCore.createSession()` is implemented)
When `isAssistant: true` is passed to `createSession()`, propagate it into the `SessionRecord` saved to `SessionStore`. The `SessionManager.createSession()` signature must accept `isAssistant?: boolean` and include it in the saved record.
### 5. Filter assistant sessions from all listings
**Files:** `src/core/sessions/session-manager.ts`, `src/plugins/api-server/routes/sessions.ts`
Filter predicate: `record.isAssistant !== true` (or `!record.isAssistant`).
Apply to:
- `SessionManager.listSessions()` — live sessions only
- `SessionManager.listAllSessions()` — live + store records
- `SessionManager.listRecords()` — raw store records
The REST `GET /sessions` route calls `listAllSessions()` and will automatically benefit from the filter there.
The `/sessions` chat command also calls `listSessions()` or `listAllSessions()` and will be filtered automatically.
### 6. Remove `/clear` command for assistant
**File:** `src/core/commands/session.ts`
Remove the `clear` command definition (currently calls `assistantManager.respawn()`).
Remove `respawn()` from `AssistantManager`.
Remove `respawn()` from `AssistantManagerCore` interface (if present).
### 7. TTL cleanup — exempt assistant sessions
**File:** `src/core/sessions/session-store.ts`
The current TTL cleanup (`cleanup()`) skips records with `status === 'active' | 'initializing'`. Since the assistant session record is written with `status: 'finished'` on shutdown (via `shutdownAll()`), it would normally be eligible for TTL deletion after `ttlDays`.
Fix: skip records where `isAssistant === true` in the `cleanup()` loop. Assistant session records must persist indefinitely (they are looked up on every restart).
---
## Affected Files Summary
| File | Change |
|------|--------|
| `src/core/types.ts` | Add `isAssistant?: boolean` to `SessionRecord` |
| `src/core/sessions/session-store.ts` | Add `findAssistant(channelId)` to interface + implementation; exempt `isAssistant` records from TTL cleanup |
| `src/core/sessions/session-manager.ts` | Pass `isAssistant` through `createSession()`; filter assistant records in `listSessions()`, `listAllSessions()`, `listRecords()` |
| `src/core/assistant/assistant-manager.ts` | Replace `spawn()` + `respawn()` with `getOrSpawn()`; update `AssistantManagerCore` interface |
| `src/core/core.ts` | Pass `isAssistant` from `createSession()` params into the session record |
| `src/core/sessions/session.ts` | Accept optional `id` override in constructor |
| `src/core/commands/session.ts` | Remove `/clear` command |
| `src/plugins/api-server/routes/sessions.ts` | No change needed (inherits filter from `listAllSessions()`) |
---
## Backward Compatibility
- Old `SessionRecord` entries without `isAssistant` field: treated as regular sessions (`isAssistant` is optional, defaults to `undefined`/falsy). No migration needed.
- If `findAssistant()` finds no existing record on first boot after upgrade: falls back to creating a new session (same as current behaviour). On the next restart, the new record is found and reused.
- Removed `/clear` command: no backward compat concern — it is a chat command, not a CLI flag or public API.
---
## Testing
- `AssistantManager.getOrSpawn()`: verify second call reuses same session ID.
- `SessionStore.findAssistant()`: verify correct lookup by channelId + isAssistant flag.
- `SessionManager.listAllSessions()`: verify assistant sessions are excluded.
- `SessionManager.listSessions()`: verify assistant sessions are excluded.
- TTL cleanup: verify assistant records are not deleted regardless of `lastActiveAt`.
- Backward compat: verify old records (no `isAssistant` field) are not excluded from listings.

View File

@ -1,129 +0,0 @@
# Design: Telegram Custom Path Wizard (No-AI Path Input)
**Date:** 2026-04-07
**Scope:** `src/plugins/telegram/commands/new-session.ts`
## Problem
When a user clicks "Custom path" in the Telegram new-session wizard, the current flow delegates to the AI assistant to collect the workspace path via natural language conversation. This is slow (waiting for AI to think and respond) and error-prone (AI may misinterpret the path or fail to validate correctly).
## Goal
Replace AI delegation for the custom path step with pure logic: bot prompts user via Telegram's Force Reply feature, user types path, bot validates immediately using existing `resolveWorkspace()`, and shows a specific error message on failure with an opportunity to retry.
## Scope
- **In scope:** Telegram adapter only — `src/plugins/telegram/commands/new-session.ts`
- **Out of scope:** Generic command handler (`session.ts` core), Slack adapter, other adapters
## Design
### State Structure
A module-level Map tracks pending force-reply sessions:
```typescript
interface ForceReplyEntry {
agentKey: string;
chatId: number;
createdAt: number; // ms timestamp for TTL
}
const forceReplyMap = new Map<number, ForceReplyEntry>();
// key = message_id of the bot's force_reply message
```
**TTL:** 10 minutes. Entries are pruned lazily on each access (no background timer needed).
### Flow
#### Step 1: User clicks "Custom path" button (`ns:custom:<agentKey>`)
1. `ctx.answerCallbackQuery()`
2. Bot sends a new message with `force_reply: true` and `selective: true`:
```
Please type the workspace path.
Examples:
• /absolute/path/to/project
• ~/my-project
• project-name (created under your base directory)
Reply to this message with your path.
```
3. Store: `forceReplyMap.set(sentMsg.message_id, { agentKey, chatId, createdAt: Date.now() })`
4. Edit the original wizard message to remove the inline keyboard (avoids stale buttons)
#### Step 2: User sends a reply
A `bot.on("message:text")` handler (registered in Telegram plugin setup) intercepts all text messages:
1. Check `ctx.message.reply_to_message?.message_id`
2. If not in `forceReplyMap` → not a path reply, ignore (let normal message handling continue)
3. If found:
- Prune expired entries (older than 10 min)
- Validate the entry is still present and not expired
- Delete entry from map
- Call `configManager.resolveWorkspace(ctx.message.text.trim())`
#### Step 3a: Validation success
- Call `createSessionDirect(agentKey, resolvedPath, ctx, core)`
- Session created, topic thread opened as normal
#### Step 3b: Validation error
- Send error message: `❌ <specific error from resolveWorkspace()>\n\nPlease try again:`
- Send a new force_reply message (same template as Step 1)
- `forceReplyMap.set(newMsg.message_id, { agentKey, chatId, createdAt: Date.now() })`
### Handler Registration
The message text handler must run **before** the default message handler (which would route messages to existing sessions). Register it early in the Telegram plugin setup with a filter:
```typescript
bot.on("message:text", async (ctx, next) => {
const replyToId = ctx.message.reply_to_message?.message_id;
if (!replyToId || !forceReplyMap.has(replyToId)) {
return next(); // not a path reply, pass through
}
await handleCustomPathReply(ctx, core, configManager);
});
```
### Error Messages
Map `resolveWorkspace()` error messages to user-friendly text:
| Error condition | Message shown |
|---|---|
| Path outside base dir, external not allowed | `Path is outside your workspace directory. Enable external workspaces in config, or use a relative name.` |
| External path does not exist | `Path does not exist: <path>. Create the directory first, then try again.` |
| Invalid workspace name (bad chars) | `Invalid name "<input>". Use only letters, numbers, hyphens, and underscores.` |
### TTL Cleanup
```typescript
function pruneExpired(): void {
const cutoff = Date.now() - 10 * 60 * 1000;
for (const [msgId, entry] of forceReplyMap) {
if (entry.createdAt < cutoff) forceReplyMap.delete(msgId);
}
}
```
Called at the start of the message:text handler before looking up the entry.
## Files Changed
| File | Change |
|---|---|
| `src/plugins/telegram/commands/new-session.ts` | Replace `ns:custom:` AI delegation with `sendForceReply()` + `handleCustomPathReply()` |
| `src/plugins/telegram/index.ts` (or bot setup file) | Register `bot.on("message:text")` handler for force-reply interception |
## What Is Not Changed
- `resolveWorkspace()` in `config.ts` — used as-is
- `createSessionDirect()` — used as-is
- Agent picker and workspace picker steps — unchanged
- Core session command handler (`session.ts`) — out of scope

View File

@ -1,6 +1,6 @@
{
"name": "@openacp/cli",
"version": "2026.408.1",
"version": "2026.403.2",
"private": true,
"license": "MIT",
"type": "module",
@ -61,7 +61,6 @@
"pino-pretty": "^13.1.3",
"pino-roll": "^4.0.0",
"qrcode-terminal": "^0.12.0",
"sanitize-html": "^2.17.2",
"zod": "^3.25.0",
"zod-to-json-schema": "^3.25.2"
},
@ -71,7 +70,6 @@
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^25.5.0",
"@types/qrcode-terminal": "^0.12.2",
"@types/sanitize-html": "^2.16.1",
"husky": "^9.1.7",
"tsup": "^8.5.1",
"tsx": "^4.21.0",

View File

@ -1,6 +1,6 @@
{
"name": "@openacp/plugin-sdk",
"version": "2026.406.3",
"version": "2026.403.2",
"description": "SDK for building OpenACP plugins — types, base classes, and testing utilities",
"type": "module",
"exports": {

View File

@ -18,9 +18,6 @@ export type {
CommandDef, CommandArgs, CommandResponse, MenuOption, ListItem,
} from '@openacp/cli'
// --- Config field types ---
export type { FieldDef } from '@openacp/cli'
// --- Service interfaces ---
export type {
SecurityService, FileServiceInterface, NotificationService,

View File

@ -1,6 +1,6 @@
import type {
PluginContext, PluginStorage, CommandDef, CommandResponse,
OutgoingMessage, MenuItem,
OutgoingMessage,
} from '@openacp/cli'
export interface TestContextOpts {
@ -112,11 +112,6 @@ export function createTestContext(opts: TestContextOpts): TestPluginContext {
registerCommand(def: CommandDef): void {
registeredCommands.set(def.name, def)
},
registerMenuItem(_item: MenuItem): void {},
unregisterMenuItem(_id: string): void {},
registerAssistantSection(_section: import('@openacp/cli').AssistantSection): void {},
unregisterAssistantSection(_id: string): void {},
registerEditableFields(_fields: import('@openacp/cli').FieldDef[]): void {},
storage,
log: silentLog,
async sendMessage(sessionId: string, content: OutgoingMessage): Promise<void> {

View File

@ -2,6 +2,7 @@ import type { InstallContext, TerminalIO, SettingsAPI } from '@openacp/cli'
export interface TestInstallContextOpts {
pluginName: string
legacyConfig?: Record<string, unknown>
terminalResponses?: Record<string, unknown[]>
}
@ -122,6 +123,7 @@ export function createTestInstallContext(opts: TestInstallContextOpts): InstallC
pluginName: opts.pluginName,
terminal,
settings,
legacyConfig: opts.legacyConfig,
dataDir: '/tmp/openacp-test-data',
log: silentLog,
// Test-specific

101
pnpm-lock.yaml generated
View File

@ -71,9 +71,6 @@ importers:
qrcode-terminal:
specifier: ^0.12.0
version: 0.12.0
sanitize-html:
specifier: ^2.17.2
version: 2.17.2
zod:
specifier: ^3.25.0
version: 3.25.76
@ -96,9 +93,6 @@ importers:
'@types/qrcode-terminal':
specifier: ^0.12.2
version: 0.12.2
'@types/sanitize-html':
specifier: ^2.16.1
version: 2.16.1
husky:
specifier: ^9.1.7
version: 9.1.7
@ -722,9 +716,6 @@ packages:
'@types/qrcode-terminal@0.12.2':
resolution: {integrity: sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==}
'@types/sanitize-html@2.16.1':
resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==}
'@vitest/expect@3.2.4':
resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}
@ -926,10 +917,6 @@ packages:
resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
engines: {node: '>=6'}
deepmerge@4.3.1:
resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}
engines: {node: '>=0.10.0'}
depd@2.0.0:
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@ -946,33 +933,12 @@ packages:
resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}
engines: {node: '>=0.3.1'}
dom-serializer@2.0.0:
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
domelementtype@2.3.0:
resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
domhandler@5.0.3:
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
engines: {node: '>= 4'}
domutils@3.2.2:
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
ecdsa-sig-formatter@1.0.11:
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
end-of-stream@1.4.5:
resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
entities@4.5.0:
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'}
entities@7.0.1:
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
engines: {node: '>=0.12'}
es-module-lexer@1.7.0:
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
@ -987,10 +953,6 @@ packages:
escape-html@1.0.3:
resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}
escape-string-regexp@4.0.0:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
estree-walker@3.0.3:
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
@ -1083,9 +1045,6 @@ packages:
help-me@5.0.0:
resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==}
htmlparser2@10.1.0:
resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
http-errors@2.0.1:
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
@ -1110,10 +1069,6 @@ packages:
resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==}
engines: {node: '>=12'}
is-plain-object@5.0.0:
resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==}
engines: {node: '>=0.10.0'}
is-unicode-supported@2.1.0:
resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==}
engines: {node: '>=18'}
@ -1347,9 +1302,6 @@ packages:
resolution: {integrity: sha512-lBX72MWFduWEf7v7uWf5DHp9Jn5BI8bNPGuFgtXMmr2uDz2Gz2749y3am3agSDdkhHPHYmmxEGSKH85ZLGzgXw==}
engines: {node: '>=20'}
parse-srcset@1.0.2:
resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}
path-scurry@2.0.2:
resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
engines: {node: 18 || 20 || >=22}
@ -1485,9 +1437,6 @@ packages:
resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}
engines: {node: '>=10'}
sanitize-html@2.17.2:
resolution: {integrity: sha512-EnffJUl46VE9uvZ0XeWzObHLurClLlT12gsOk1cHyP2Ol1P0BnBnsXmShlBmWVJM+dKieQI68R0tsPY5m/B+Jg==}
secure-json-parse@4.1.0:
resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==}
@ -2294,10 +2243,6 @@ snapshots:
'@types/qrcode-terminal@0.12.2': {}
'@types/sanitize-html@2.16.1':
dependencies:
htmlparser2: 10.1.0
'@vitest/expect@3.2.4':
dependencies:
'@types/chai': 5.2.3
@ -2487,8 +2432,6 @@ snapshots:
deep-eql@5.0.2: {}
deepmerge@4.3.1: {}
depd@2.0.0: {}
dequal@2.0.3: {}
@ -2497,24 +2440,6 @@ snapshots:
diff@8.0.3: {}
dom-serializer@2.0.0:
dependencies:
domelementtype: 2.3.0
domhandler: 5.0.3
entities: 4.5.0
domelementtype@2.3.0: {}
domhandler@5.0.3:
dependencies:
domelementtype: 2.3.0
domutils@3.2.2:
dependencies:
dom-serializer: 2.0.0
domelementtype: 2.3.0
domhandler: 5.0.3
ecdsa-sig-formatter@1.0.11:
dependencies:
safe-buffer: 5.2.1
@ -2523,10 +2448,6 @@ snapshots:
dependencies:
once: 1.4.0
entities@4.5.0: {}
entities@7.0.1: {}
es-module-lexer@1.7.0: {}
es-module-lexer@2.0.0: {}
@ -2562,8 +2483,6 @@ snapshots:
escape-html@1.0.3: {}
escape-string-regexp@4.0.0: {}
estree-walker@3.0.3:
dependencies:
'@types/estree': 1.0.8
@ -2672,13 +2591,6 @@ snapshots:
help-me@5.0.0: {}
htmlparser2@10.1.0:
dependencies:
domelementtype: 2.3.0
domhandler: 5.0.3
domutils: 3.2.2
entities: 7.0.1
http-errors@2.0.1:
dependencies:
depd: 2.0.0
@ -2697,8 +2609,6 @@ snapshots:
is-interactive@2.0.0: {}
is-plain-object@5.0.0: {}
is-unicode-supported@2.1.0: {}
joycon@3.1.1: {}
@ -2906,8 +2816,6 @@ snapshots:
stdin-discarder: 0.3.1
string-width: 8.2.0
parse-srcset@1.0.2: {}
path-scurry@2.0.2:
dependencies:
lru-cache: 11.2.7
@ -3078,15 +2986,6 @@ snapshots:
safe-stable-stringify@2.5.0: {}
sanitize-html@2.17.2:
dependencies:
deepmerge: 4.3.1
escape-string-regexp: 4.0.0
htmlparser2: 10.1.0
is-plain-object: 5.0.0
parse-srcset: 1.0.2
postcss: 8.5.8
secure-json-parse@4.1.0: {}
semver@7.7.4: {}

View File

@ -30,8 +30,6 @@ $ERROR_C = "$ESC[38;2;239;68;68m" # red #ef4444
$MUTED = "$ESC[38;2;90;100;128m" # text-muted #5a6480
$NC = "$ESC[0m"
$INSTALLER_VERSION = "1.0.1"
$NODE_MIN_MAJOR = 20
function Write-Msg {
@ -52,7 +50,6 @@ function Write-Banner {
Write-Host ""
Write-Host "${ACCENT}${BOLD} OpenACP Installer${NC}"
Write-Host "${MUTED} AI coding agents, anywhere.${NC}"
Write-Host "${MUTED} installer v$INSTALLER_VERSION${NC}"
Write-Host ""
}
@ -207,29 +204,14 @@ function Resolve-PackageInstallSpec {
return "@openacp/cli@$RequestedTag"
}
function Resolve-NpmExecutable {
# Node for Windows ships npm.ps1, which rebuilds argv via PowerShell's parser. Scoped package
# names (@scope/pkg) break that and npm may report Unknown command "pm". npm.cmd calls node
# directly and does not have this bug.
$nodeCmd = Get-Command node -ErrorAction SilentlyContinue
if ($nodeCmd -and $nodeCmd.Source) {
$npmCmd = Join-Path (Split-Path -Parent $nodeCmd.Source) 'npm.cmd'
if (Test-Path -LiteralPath $npmCmd) {
return $npmCmd
}
}
return 'npm'
}
# ─── Section 6: Install via npm ──────────────────────────────────────────────
function Install-OpenACPNpm {
$npmExe = Resolve-NpmExecutable
$spec = Resolve-PackageInstallSpec -RequestedTag $Tag
Write-Msg -Level info -Message "Installing $spec globally via npm..."
if ($DryRun) {
Write-Msg -Level info -Message "[dry-run] Would run: npm install -g -- `"$spec`""
Write-Msg -Level info -Message "[dry-run] Would run: npm install -g $spec"
return
}
@ -241,7 +223,7 @@ function Install-OpenACPNpm {
while ($attempt -lt $maxRetries) {
$attempt++
try {
$lastOutput = & $npmExe install -g -- "$spec" 2>&1
$lastOutput = & npm install -g $spec 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Msg -Level success -Message "Installed $spec via npm"
return
@ -253,7 +235,7 @@ function Install-OpenACPNpm {
} catch {
$lastOutput = "$_"
if ($attempt -lt $maxRetries) {
Write-Msg -Level warn -Message "npm install error (attempt $attempt/$maxRetries): $_ - retrying in ${retryDelay}s..."
Write-Msg -Level warn -Message "npm install error (attempt $attempt/$maxRetries): $_ — retrying in ${retryDelay}s..."
Start-Sleep -Seconds $retryDelay
}
}
@ -408,9 +390,8 @@ function Main {
$env:Path = [System.Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path', 'User')
# Find npm global bin and ensure it's in user PATH
$npmExe = Resolve-NpmExecutable
try {
$npmPrefix = (& $npmExe prefix -g 2>$null).Trim()
$npmPrefix = (& npm prefix -g 2>$null).Trim()
if ($npmPrefix) {
Add-ToPath -Dir $npmPrefix
}
@ -433,8 +414,7 @@ function Main {
if (-not $openacp) {
# Also check npm global prefix directly
try {
$npmForPrefix = Resolve-NpmExecutable
$npmPrefix = (& $npmForPrefix prefix -g 2>$null).Trim()
$npmPrefix = (& npm prefix -g 2>$null).Trim()
if ($npmPrefix -and (Test-Path (Join-Path $npmPrefix 'openacp.cmd'))) {
$env:Path = "$env:Path;$npmPrefix"
Add-ToPath -Dir $npmPrefix

View File

@ -15,23 +15,12 @@ ERROR='\033[38;2;239;68;68m' # red #ef4444
MUTED='\033[38;2;90;100;128m' # text-muted #5a6480
NC='\033[0m'
INSTALLER_VERSION="1.0.3"
DEFAULT_TAGLINE="AI coding agents, anywhere."
NODE_DEFAULT_MAJOR=20
NODE_MIN_MAJOR=20
NODE_MIN_MINOR=0
NODE_MIN_VERSION="${NODE_MIN_MAJOR}.${NODE_MIN_MINOR}"
# Initialize Homebrew PATH for non-login shells (macOS).
# ~/.zprofile is not sourced when running as 'bash install.sh' or 'curl | bash',
# so /opt/homebrew/bin (Apple Silicon) or /usr/local/bin (Intel) may be missing from PATH.
if [[ -x "/opt/homebrew/bin/brew" ]]; then
eval "$(/opt/homebrew/bin/brew shellenv)" 2>/dev/null || true
elif [[ -x "/usr/local/bin/brew" ]]; then
eval "$(/usr/local/bin/brew shellenv)" 2>/dev/null || true
fi
ORIGINAL_PATH="${PATH:-}"
TMPFILES=()
@ -250,7 +239,7 @@ print_installer_banner() {
local title tagline hint card
title="$("$GUM" style --foreground "#6366f1" --bold "⚡ OpenACP Installer")"
tagline="$("$GUM" style --foreground "#8892b0" "$TAGLINE")"
hint="$("$GUM" style --foreground "#5a6480" "installer v${INSTALLER_VERSION}")"
hint="$("$GUM" style --foreground "#5a6480" "modern installer mode")"
card="$(printf '%s\n%s\n%s' "$title" "$tagline" "$hint")"
"$GUM" style --border rounded --border-foreground "#6366f1" --padding "1 2" "$card"
echo ""
@ -260,7 +249,6 @@ print_installer_banner() {
echo -e "${ACCENT}${BOLD}"
echo " ⚡ OpenACP Installer"
echo -e "${NC}${INFO} ${TAGLINE}${NC}"
echo -e "${MUTED} installer v${INSTALLER_VERSION}${NC}"
echo ""
}
@ -698,13 +686,11 @@ node_is_at_least_required() {
check_node() {
if command -v node &>/dev/null; then
local node_path
node_path="$(command -v node)"
if node_is_at_least_required; then
ui_success "Node.js v$(node -v | cut -d'v' -f2) found (${node_path})"
ui_success "Node.js v$(node -v | cut -d'v' -f2) found"
return 0
else
ui_info "Node.js $(node -v) found at ${node_path}, need v${NODE_MIN_VERSION}+"
ui_info "Node.js $(node -v) found, need v${NODE_MIN_VERSION}+"
return 1
fi
else
@ -714,28 +700,14 @@ check_node() {
}
ensure_default_node_active_shell() {
# Always try version managers first (nvm, fnm, nodenv) before falling back to
# system node. This is important because version-manager-installed node has a
# user-writable npm prefix, whereas system node (installed via pkg/brew without
# a version manager) typically uses /usr/local which may require sudo for global
# installs — even when the node version itself meets the minimum requirement.
# Try sourcing nvm.
# Check NVM_DIR first, then fall back to the default ~/.nvm location.
# The fallback is critical: in non-login shells (e.g. when launched from a
# GUI app like the OpenACP desktop), ~/.zshrc is never sourced so NVM_DIR
# is unset even when nvm is properly installed.
local nvm_sh=""
if [[ -n "${NVM_DIR:-}" && -s "${NVM_DIR}/nvm.sh" ]]; then
nvm_sh="${NVM_DIR}/nvm.sh"
elif [[ -s "${HOME}/.nvm/nvm.sh" ]]; then
nvm_sh="${HOME}/.nvm/nvm.sh"
elif [[ -n "${XDG_CONFIG_HOME:-}" && -s "${XDG_CONFIG_HOME}/nvm/nvm.sh" ]]; then
nvm_sh="${XDG_CONFIG_HOME}/nvm/nvm.sh"
if node_is_at_least_required; then
return 0
fi
if [[ -n "$nvm_sh" ]]; then
# Try sourcing nvm
if [[ -n "${NVM_DIR:-}" && -s "${NVM_DIR}/nvm.sh" ]]; then
# shellcheck source=/dev/null
source "$nvm_sh" 2>/dev/null || true
source "${NVM_DIR}/nvm.sh" 2>/dev/null || true
if node_is_at_least_required; then
return 0
fi
@ -757,23 +729,6 @@ ensure_default_node_active_shell() {
fi
fi
# Fall back to whatever node is already in PATH (system node, Homebrew, etc.)
if node_is_at_least_required; then
return 0
fi
# Try Homebrew-managed Node (macOS) — covers cases where Homebrew shellenv
# was not initialized (e.g. non-login shell without ~/.zprofile sourced).
for brew_bin in "/opt/homebrew/bin" "/usr/local/bin"; do
if [[ -x "${brew_bin}/node" ]]; then
export PATH="${brew_bin}:${PATH}"
hash -r 2>/dev/null || true
if node_is_at_least_required; then
return 0
fi
fi
done
return 1
}
@ -786,52 +741,6 @@ print_nvm_upgrade_hint() {
echo "Then open a new shell and rerun the installer."
}
# Ensure nvm init lines are present in all relevant shell config files.
# nvm's own installer only writes based on $SHELL, which may miss some configs.
# On macOS the primary shell is zsh — always patch ~/.zshrc regardless of other rc files.
patch_nvm_shell_configs() {
# shellcheck disable=SC2016
local nvm_init_lines
nvm_init_lines="$(cat <<'EOF'
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
EOF
)"
local marker='nvm.sh'
patch_rc() {
local rc="$1"
if ! grep -q "$marker" "$rc" 2>/dev/null; then
printf '\n# nvm (Node Version Manager)\n%s\n' "$nvm_init_lines" >> "$rc"
ui_info "Added nvm init to $rc"
fi
}
if [[ "$OS" == "macos" ]]; then
# macOS default shell is zsh. On a fresh machine ~/.zshrc may not exist yet —
# nvm installer only appends to existing files, so we must ensure ~/.zshrc exists.
touch "$HOME/.zshrc"
patch_rc "$HOME/.zshrc"
# Also patch bash configs if they exist
for rc in "$HOME/.bashrc" "$HOME/.bash_profile"; do
[[ -f "$rc" ]] && patch_rc "$rc"
done
else
# Linux: patch whichever rc files exist; create ~/.bashrc if none present
local patched_any=0
for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile"; do
if [[ -f "$rc" ]]; then
patch_rc "$rc"
patched_any=1
fi
done
if [[ "$patched_any" -eq 0 ]]; then
printf '# nvm (Node Version Manager)\n%s\n' "$nvm_init_lines" > "$HOME/.bashrc"
ui_info "Created ~/.bashrc with nvm init"
fi
fi
}
install_node() {
if [[ "$OS" == "macos" ]]; then
ensure_xcode_clt
@ -845,7 +754,6 @@ install_node() {
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
# shellcheck source=/dev/null
[[ -s "${NVM_DIR}/nvm.sh" ]] && source "${NVM_DIR}/nvm.sh"
patch_nvm_shell_configs
fi
if [[ -s "${NVM_DIR:-${HOME}/.nvm}/nvm.sh" ]]; then
@ -860,10 +768,6 @@ install_node() {
exit 1
fi
# Always ensure shell configs are patched (idempotent) — handles the case where
# nvm was already installed but ~/.zshrc didn't exist at that time.
patch_nvm_shell_configs
ui_success "Node.js v${NODE_DEFAULT_MAJOR} installed"
elif [[ "$OS" == "linux" ]]; then
@ -879,7 +783,6 @@ install_node() {
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
# shellcheck source=/dev/null
[[ -s "${NVM_DIR}/nvm.sh" ]] && source "${NVM_DIR}/nvm.sh"
patch_nvm_shell_configs
fi
if [[ -n "${NVM_DIR:-}" && -s "${NVM_DIR}/nvm.sh" ]] || [[ -s "${HOME}/.nvm/nvm.sh" ]]; then
@ -944,11 +847,6 @@ install_node() {
fi
fi
# Always ensure shell configs are patched (idempotent)
if [[ -s "${HOME}/.nvm/nvm.sh" ]] || [[ -s "${NVM_DIR:-}/nvm.sh" ]]; then
patch_nvm_shell_configs
fi
ui_success "Node.js v${NODE_DEFAULT_MAJOR} installed"
fi
}
@ -1044,22 +942,17 @@ install_git() {
}
fix_npm_permissions() {
if [[ "$OS" != "linux" ]]; then
return 0
fi
local npm_prefix
npm_prefix="$(npm config get prefix 2>/dev/null || true)"
if [[ -z "$npm_prefix" ]]; then
return 0
fi
# Check if npm global installs would succeed by verifying write access to the
# node_modules directory specifically. Checking $prefix or $prefix/lib alone is
# not sufficient: on Intel Macs with Homebrew, /usr/local/lib is user-writable
# (Homebrew sets this up) but /usr/local/lib/node_modules may be owned by root
# if Node was previously installed via the official pkg installer.
local nm_dir="$npm_prefix/lib/node_modules"
if [[ -d "$nm_dir" && -w "$nm_dir" ]]; then
return 0
fi
if [[ ! -d "$nm_dir" && -w "$npm_prefix/lib" ]]; then
if [[ -w "$npm_prefix" || -w "$npm_prefix/lib" ]]; then
return 0
fi
@ -1327,18 +1220,9 @@ warn_path_missing() {
if [[ -z "$dir" ]]; then
return 0
fi
# Skip if already present in the original PATH (before nvm/npm were loaded)
case ":${ORIGINAL_PATH}:" in
*":${dir}:"*) return 0 ;;
esac
# Also skip if this dir is inside the nvm prefix — nvm adds itself to PATH via
# shell rc files automatically, so no manual PATH fix is needed.
if [[ -n "${NVM_DIR:-}" && "$dir" == "${NVM_DIR}"* ]]; then
return 0
fi
if [[ "$dir" == "${HOME}/.nvm"* ]]; then
return 0
fi
echo ""
ui_warn "PATH missing ${label}: ${dir}"
@ -1374,14 +1258,6 @@ main() {
# ── Stage 1: Prepare environment ──
ui_stage "Preparing environment"
# Attempt to activate an existing node installation (e.g. via nvm, fnm, nodenv,
# or Homebrew) before checking whether node is present. This is necessary because
# the script may run in a non-login shell (e.g. launched from a GUI app) where
# shell rc files are never sourced and PATH-based node managers are invisible.
# If activation fails silently here that is fine — check_node / install_node below
# will handle the missing-node case.
ensure_default_node_active_shell 2>/dev/null || true
if ! check_node; then
install_node
fi
@ -1402,10 +1278,6 @@ main() {
# ── Stage 2: Install ──
ui_stage "Installing OpenACP"
# Fix npm permissions before any npm global install, regardless of install method.
# Both "npm" and "git" paths may call `npm install -g` (pnpm, openacp).
fix_npm_permissions
if [[ "$INSTALL_METHOD" == "git" ]]; then
if ! check_git; then
install_git
@ -1417,6 +1289,8 @@ main() {
fi
install_openacp_from_git "$GIT_DIR"
else
fix_npm_permissions
local install_spec=""
install_spec="$(resolve_package_install_spec "$INSTALL_TAG")"
install_openacp_npm "$install_spec"
@ -1471,14 +1345,6 @@ main() {
ui_kv "Wrapper" "$HOME/.local/bin/openacp"
fi
# If nvm was used to install Node, the current shell session doesn't have nvm sourced yet.
# Instruct user to open a new terminal (the simplest and most reliable approach).
if [[ -s "${NVM_DIR:-${HOME}/.nvm}/nvm.sh" ]]; then
echo ""
ui_warn "Open a new terminal tab/window before running openacp"
echo " (nvm needs to be loaded, which happens automatically in new terminals)"
fi
if [[ "$NO_ONBOARD" != "1" ]]; then
if [[ -n "$OPENACP_BIN" && -r /dev/tty && -w /dev/tty ]]; then
ui_info "Starting setup wizard..."
@ -1486,10 +1352,10 @@ main() {
exec </dev/tty
exec "$OPENACP_BIN"
else
ui_info "Then run: openacp"
ui_info "Run openacp to start the setup wizard"
fi
else
ui_info "Then run: openacp"
ui_info "Run openacp to get started"
fi
}

View File

@ -32,7 +32,7 @@ function createMockSession() {
setName: vi.fn(),
finish: vi.fn(),
fail: vi.fn(),
updateConfigOptions: vi.fn().mockResolvedValue(undefined),
updateConfigOptions: vi.fn(),
toAcpStateSnapshot: vi.fn().mockReturnValue({}),
}) as unknown as Session
}

View File

@ -26,7 +26,6 @@ describe("ApiServer", () => {
sessionManager: {
getSession: vi.fn(),
listSessions: vi.fn(() => []),
listAllSessions: vi.fn(() => []),
listRecords: vi.fn(() => []),
updateSessionDangerousMode: vi.fn(), // legacy — kept for backward compat tests
patchRecord: vi.fn(),
@ -37,13 +36,22 @@ describe("ApiServer", () => {
getAvailableAgents: vi.fn(() => []),
},
agentCatalog: {
load: vi.fn(),
resolve: vi.fn((name: string) => ({ name, workingDirectory: "/tmp/ws" })),
},
configManager: {
get: vi.fn(() => ({
defaultAgent: "claude",
agents: { claude: { command: "claude-agent-acp", args: [], env: {} } },
agents: {
claude: { command: "claude", args: [], workingDirectory: "/tmp/ws" },
},
security: {
maxConcurrentSessions: 5,
sessionTimeoutMinutes: 60,
allowedUserIds: [],
},
channels: {
telegram: { enabled: false, botToken: "secret-token", chatId: 0 },
},
workspace: { baseDir: "~/openacp-workspace" },
logging: {
level: "info",
@ -52,11 +60,23 @@ describe("ApiServer", () => {
maxFiles: 7,
sessionLogRetentionDays: 30,
},
tunnel: {
enabled: true,
port: 3100,
provider: "cloudflare",
options: {},
storeTtlMinutes: 60,
auth: { enabled: false },
},
sessionStore: { ttlDays: 30 },
runMode: "foreground",
autoStart: false,
api: { port: 21420, host: "127.0.0.1" },
integrations: {},
agentSwitch: { labelHistory: true },
speech: {
stt: { provider: null, providers: {} },
tts: { provider: null, providers: {} },
},
})),
save: vi.fn(),
setPath: vi.fn(),
@ -69,9 +89,6 @@ describe("ApiServer", () => {
updatePluginSettings: vi.fn().mockResolvedValue(undefined),
},
adapters: new Map(),
getOrResumeSessionById: vi.fn((id: string) =>
Promise.resolve(mockCore.sessionManager.getSession(id))
),
notificationManager: { notifyAll: vi.fn() },
requestRestart: vi.fn(),
tunnelService: undefined as unknown,
@ -95,7 +112,7 @@ describe("ApiServer", () => {
} catch { /* ignore */ }
});
async function startServer(portOverride?: number, lifecycleManagerOverride?: unknown) {
async function startServer(portOverride?: number) {
// Create or load the test secret
const dir = path.dirname(secretFilePath);
fs.mkdirSync(dir, { recursive: true });
@ -134,16 +151,13 @@ describe("ApiServer", () => {
const authPreHandler = createAuthPreHandler(() => secret, () => jwtSecret, tokenStore);
const deps: Record<string, unknown> = {
const deps = {
core: mockCore as any,
topicManager: mockTopicManager as any,
startedAt: Date.now(),
getVersion: () => "0.0.0-dev",
authPreHandler,
};
if (lifecycleManagerOverride !== undefined) {
deps.lifecycleManager = lifecycleManagerOverride;
}
server.registerPlugin('/api/v1/sessions', async (app: any) => sessionRoutes(app, deps));
server.registerPlugin('/api/v1/agents', async (app: any) => agentRoutes(app, deps));
@ -299,13 +313,7 @@ describe("ApiServer", () => {
{ status: "active" },
{ status: "initializing" },
]);
// Provide lifecycleManager with settingsManager returning maxConcurrentSessions=5
const mockLifecycleManager = {
settingsManager: {
loadSettings: vi.fn().mockResolvedValue({ maxConcurrentSessions: 5 }),
},
};
const port = await startServer(undefined, mockLifecycleManager);
const port = await startServer();
const res = await apiFetch(port, "/api/v1/sessions", { method: "POST" });
expect(res.status).toBe(429);
@ -354,38 +362,28 @@ describe("ApiServer", () => {
});
it("GET /api/sessions returns session list", async () => {
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([
mockCore.sessionManager.listSessions.mockReturnValueOnce([
{
id: "abc",
agent: "claude",
agentName: "claude",
status: "active",
name: "Fix bug",
workspace: "/tmp/a",
channelId: "api",
createdAt: "2026-01-01T00:00:00.000Z",
lastActiveAt: null,
dangerousMode: false,
workingDirectory: "/tmp/a",
createdAt: new Date("2026-01-01T00:00:00Z"),
clientOverrides: { bypassPermissions: false },
queueDepth: 0,
promptRunning: false,
configOptions: undefined,
capabilities: null,
isLive: true,
},
{
id: "def",
agent: "codex",
agentName: "codex",
status: "initializing",
name: null,
workspace: "/tmp/b",
channelId: "api",
createdAt: "2026-01-02T00:00:00.000Z",
lastActiveAt: null,
dangerousMode: false,
name: undefined,
workingDirectory: "/tmp/b",
createdAt: new Date("2026-01-02T00:00:00Z"),
clientOverrides: { bypassPermissions: false },
queueDepth: 0,
promptRunning: false,
configOptions: undefined,
capabilities: null,
isLive: true,
},
]);
const port = await startServer();
@ -412,24 +410,20 @@ describe("ApiServer", () => {
it("GET /api/sessions returns extended fields", async () => {
const created = new Date("2026-01-01T00:00:00Z");
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([
mockCore.sessionManager.listSessions.mockReturnValueOnce([
{
id: "abc",
agent: "claude",
agentName: "claude",
status: "active",
name: "Test",
workspace: "/tmp",
channelId: "api",
createdAt: created.toISOString(),
lastActiveAt: null,
dangerousMode: true,
workingDirectory: "/tmp",
createdAt: created,
clientOverrides: { bypassPermissions: true },
queueDepth: 2,
promptRunning: true,
configOptions: undefined,
capabilities: null,
isLive: true,
},
]);
mockCore.sessionManager.getSessionRecord.mockReturnValueOnce(null);
const port = await startServer();
const res = await apiFetch(port, "/api/v1/sessions");
@ -581,22 +575,7 @@ describe("ApiServer", () => {
// ===== New endpoint tests =====
it("GET /api/health returns basic system health (public endpoint)", async () => {
const port = await startServer();
// Public /health endpoint returns minimal info only (no auth required)
const res = await apiFetch(port, "/api/v1/system/health");
expect(res.status).toBe(200);
const data = await res.json();
expect(data.status).toBe("ok");
expect(data.version).toBeDefined();
expect(typeof data.uptime).toBe("number");
// Sensitive details (memory, sessions, adapters) are on /health/details — not here
expect(data.memory).toBeUndefined();
expect(data.sessions).toBeUndefined();
});
it("GET /api/health/details returns full system health (authenticated)", async () => {
it("GET /api/health returns system health", async () => {
mockCore.sessionManager.listSessions.mockReturnValueOnce([
{ status: "active" },
{ status: "initializing" },
@ -610,7 +589,7 @@ describe("ApiServer", () => {
]);
const port = await startServer();
const res = await apiFetch(port, "/api/v1/system/health/details");
const res = await apiFetch(port, "/api/v1/system/health");
expect(res.status).toBe(200);
const data = await res.json();
expect(data.status).toBe("ok");
@ -664,6 +643,7 @@ describe("ApiServer", () => {
expect(res.status).toBe(200);
const data = await res.json();
expect(data.config).toBeDefined();
expect(data.config.channels.telegram.botToken).toBe("***");
expect(data.config.defaultAgent).toBe("claude");
});
@ -687,7 +667,7 @@ describe("ApiServer", () => {
const data = await res.json();
expect(data.ok).toBe(true);
expect(data.sessionId).toBe("abc123");
expect(mockSession.enqueuePrompt).toHaveBeenCalledWith("Hello world", undefined, expect.objectContaining({ sourceAdapterId: "api" }), expect.any(String));
expect(mockSession.enqueuePrompt).toHaveBeenCalledWith("Hello world");
});
it("POST /api/sessions/:id/prompt returns 404 for unknown session", async () => {
@ -846,7 +826,7 @@ describe("ApiServer", () => {
expect(res.status).toBe(400);
const data = await res.json();
expect(data.error).toContain("Required");
expect(data.error).toContain("Missing message");
});
it("POST /api/restart returns 200 and triggers restart", async () => {
@ -1008,23 +988,23 @@ describe("ApiServer", () => {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
path: "logging.level",
value: "debug",
path: "security.maxConcurrentSessions",
value: 10,
}),
});
const data1 = (await res1.json()) as any;
expect(data1.ok).toBe(true);
expect(data1.needsRestart).toBe(false);
// Unknown/unsafe field — should return 403
// Non-hot-reloadable field — should need restart
const res2 = await apiFetch(port, "/api/v1/config", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path: "nonexistent.field", value: false }),
body: JSON.stringify({ path: "tunnel.enabled", value: false }),
});
const data2 = (await res2.json()) as any;
expect(res2.status).toBe(403);
expect(data2.error).toContain("cannot be modified");
expect(data2.ok).toBe(true);
expect(data2.needsRestart).toBe(true);
});
it("GET /api/events returns SSE headers", async () => {
@ -1444,12 +1424,12 @@ describe("ApiServer", () => {
it("rejects invalid config values (string for number field)", async () => {
const port = await startServer();
// Pass a string where the field expects a number (sessionStore.ttlDays is a number field in registry)
// Pass a string where the field expects a number
const res = await apiFetch(port, "/api/v1/config", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
path: "sessionStore.ttlDays",
path: "security.maxConcurrentSessions",
value: "not-a-number",
}),
});
@ -1464,6 +1444,17 @@ describe("ApiServer", () => {
it("redacts sensitive keys inside arrays", async () => {
mockCore.configManager.get.mockReturnValueOnce({
defaultAgent: "claude",
agents: {
claude: { command: "claude", args: [], workingDirectory: "/tmp/ws" },
},
security: {
maxConcurrentSessions: 5,
sessionTimeoutMinutes: 60,
allowedUserIds: [],
},
channels: {
telegram: { enabled: false, botToken: "secret-token", chatId: 0 },
},
workspace: { baseDir: "~/openacp-workspace" },
logging: {
level: "info",
@ -1472,16 +1463,24 @@ describe("ApiServer", () => {
maxFiles: 7,
sessionLogRetentionDays: 30,
},
tunnel: {
enabled: true,
port: 3100,
provider: "cloudflare",
options: {},
storeTtlMinutes: 60,
auth: { enabled: false },
},
sessionStore: { ttlDays: 30 },
runMode: "foreground",
autoStart: false,
api: { port: 21420, host: "127.0.0.1" },
integrations: {
webhooks: [
{ name: "webhook1", token: "super-secret-token" },
{ name: "webhook2", token: "another-secret" },
],
},
agentSwitch: { labelHistory: true },
});
const port = await startServer();
@ -1520,8 +1519,10 @@ describe("ApiServer", () => {
});
it("allows health endpoint without auth", async () => {
mockCore.sessionManager.listSessions.mockReturnValueOnce([]);
mockCore.sessionManager.listRecords.mockReturnValueOnce([]);
const port = await startServer();
// Use raw fetch without auth — public /health requires no token
// Use raw fetch without auth
const res = await globalThis.fetch(`http://127.0.0.1:${port}/api/v1/system/health`);
expect(res.status).toBe(200);
});
@ -1535,7 +1536,7 @@ describe("ApiServer", () => {
});
it("accepts requests with valid auth token", async () => {
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([]);
mockCore.sessionManager.listSessions.mockReturnValueOnce([]);
const port = await startServer();
const token = readTestSecret();
const res = await globalThis.fetch(

View File

@ -304,17 +304,17 @@ describe('CLI command args parsing', () => {
describe('cmdInstall', () => {
it('parses package name from args[0]', () => {
const { args } = simulateDispatch(['install', '@openacp/discord-adapter'])
const { args } = simulateDispatch(['install', '@openacp/adapter-discord'])
const pkg = args[0]
expect(pkg).toBe('@openacp/discord-adapter')
expect(pkg).toBe('@openacp/adapter-discord')
})
})
describe('cmdUninstall', () => {
it('parses package name from args[0]', () => {
const { args } = simulateDispatch(['uninstall', '@openacp/discord-adapter'])
const { args } = simulateDispatch(['uninstall', '@openacp/adapter-discord'])
const pkg = args[0]
expect(pkg).toBe('@openacp/discord-adapter')
expect(pkg).toBe('@openacp/adapter-discord')
})
})
@ -332,9 +332,9 @@ describe('CLI command args parsing', () => {
})
it('parses install package from args[1]', () => {
const { args } = simulateDispatch(['plugin', 'add', '@openacp/discord-adapter'])
const { args } = simulateDispatch(['plugin', 'add', '@openacp/adapter-discord'])
expect(args[0]).toBe('add')
expect(args[1]).toBe('@openacp/discord-adapter')
expect(args[1]).toBe('@openacp/adapter-discord')
})
})
})

View File

@ -3,6 +3,8 @@ import { ConfigSchema, ConfigManager } from '../core/config/config.js'
describe('ConfigSchema - runMode and autoStart', () => {
const baseConfig = {
channels: { telegram: { enabled: false } },
agents: { claude: { command: 'claude-agent-acp', args: [], env: {} } },
defaultAgent: 'claude',
}
@ -31,70 +33,42 @@ describe('ConfigSchema - runMode and autoStart', () => {
})
})
describe('ConfigSchema - api', () => {
const baseConfig = {
channels: { telegram: { enabled: false } },
agents: { claude: { command: 'claude-agent-acp', args: [], env: {} } },
defaultAgent: 'claude',
}
it('defaults api.port to 21420 and api.host to 127.0.0.1', () => {
const result = ConfigSchema.parse(baseConfig)
expect(result.api.port).toBe(21420)
expect(result.api.host).toBe('127.0.0.1')
})
it('accepts custom api port', () => {
const result = ConfigSchema.parse({ ...baseConfig, api: { port: 9999 } })
expect(result.api.port).toBe(9999)
expect(result.api.host).toBe('127.0.0.1')
})
})
describe('ConfigManager.get() immutability', () => {
it('returns a clone — mutating result does not affect internal config', async () => {
const mgr = new ConfigManager()
// Manually set config via private field for isolated unit test
;(mgr as any).config = ConfigSchema.parse({
channels: { telegram: { enabled: false } },
agents: { claude: { command: 'claude-agent-acp', args: [], env: {} } },
defaultAgent: 'claude',
})
const config1 = mgr.get()
config1.defaultAgent = 'MUTATED'
;(config1.security as any).maxConcurrentSessions = 999
const config2 = mgr.get()
expect(config2.defaultAgent).toBe('claude')
})
})
describe('ConfigSchema — removed legacy fields', () => {
it('strips channels field from parsed output', () => {
const result = ConfigSchema.safeParse({
defaultAgent: 'claude',
channels: { telegram: { botToken: 'tok', chatId: 0, enabled: true } },
})
expect(result.success).toBe(true)
expect((result.data as any).channels).toBeUndefined()
})
it('strips top-level security field from parsed output', () => {
const result = ConfigSchema.safeParse({
defaultAgent: 'claude',
security: { allowedUserIds: [], maxConcurrentSessions: 5 },
})
expect(result.success).toBe(true)
expect((result.data as any).security).toBeUndefined()
})
it('strips tunnel field from parsed output', () => {
const result = ConfigSchema.safeParse({
defaultAgent: 'claude',
tunnel: { enabled: true, port: 3100 },
})
expect(result.success).toBe(true)
expect((result.data as any).tunnel).toBeUndefined()
})
})
describe('ConfigSchema — core fields', () => {
it('parses outputMode correctly', () => {
const result = ConfigSchema.safeParse({ defaultAgent: 'claude', outputMode: 'high' })
expect(result.success).toBe(true)
expect(result.data!.outputMode).toBe('high')
})
it('parses agentSwitch.labelHistory correctly', () => {
const result = ConfigSchema.safeParse({
defaultAgent: 'claude',
agentSwitch: { labelHistory: false },
})
expect(result.success).toBe(true)
expect(result.data!.agentSwitch.labelHistory).toBe(false)
})
it('defaults agentSwitch.labelHistory to true', () => {
const result = ConfigSchema.safeParse({ defaultAgent: 'claude' })
expect(result.success).toBe(true)
expect(result.data!.agentSwitch.labelHistory).toBe(true)
expect(config2.security.maxConcurrentSessions).toBe(20)
})
})

View File

@ -35,8 +35,11 @@ describe('ConfigManager.resolveWorkspace', () => {
// Write a valid config
const config = {
channels: { telegram: { enabled: false, botToken: 'test', chatId: 0 } },
defaultAgent: 'claude',
workspace: { baseDir: path.join(tmpDir, 'workspace') },
agents: {},
security: { allowedUserIds: [], maxConcurrentSessions: 20, sessionTimeoutMinutes: 60 },
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2))
@ -55,34 +58,15 @@ describe('ConfigManager.resolveWorkspace', () => {
expect(fs.existsSync(result)).toBe(true)
})
it('allows absolute path outside baseDir when allowExternalWorkspaces is true (default)', async () => {
it('rejects absolute path outside baseDir', async () => {
await configManager.load()
// /tmp exists on all systems; with allowExternalWorkspaces: true (default) it should be accepted
const result = configManager.resolveWorkspace('/tmp')
expect(result).toBe('/tmp')
expect(() => configManager.resolveWorkspace('/tmp/outside-workspace')).toThrow(/outside base directory/)
})
it('rejects absolute path outside baseDir when allowExternalWorkspaces is false', async () => {
// Write config with allowExternalWorkspaces: false
const configPath = path.join(tmpDir, 'config.json')
fs.writeFileSync(configPath, JSON.stringify({
defaultAgent: 'claude',
workspace: { baseDir: path.join(tmpDir, 'workspace'), allowExternalWorkspaces: false },
}, null, 2))
const restrictedManager = new ConfigManager(configPath)
await restrictedManager.load()
expect(() => restrictedManager.resolveWorkspace('/tmp/outside-workspace')).toThrow(/outside base directory/)
})
it('rejects tilde path outside baseDir when allowExternalWorkspaces is false', async () => {
const configPath = path.join(tmpDir, 'config.json')
fs.writeFileSync(configPath, JSON.stringify({
defaultAgent: 'claude',
workspace: { baseDir: path.join(tmpDir, 'workspace'), allowExternalWorkspaces: false },
}, null, 2))
const restrictedManager = new ConfigManager(configPath)
await restrictedManager.load()
expect(() => restrictedManager.resolveWorkspace('~/outside-workspace-openacp-test')).toThrow(/outside base directory/)
it('rejects tilde path outside baseDir', async () => {
await configManager.load()
// Use a tilde path that resolves outside the tmpDir-based baseDir
expect(() => configManager.resolveWorkspace('~/outside-workspace-openacp-test')).toThrow(/outside base directory/)
})
it('allows absolute path under baseDir', async () => {
@ -138,16 +122,25 @@ describe('ConfigManager.applyEnvOverrides', () => {
afterEach(() => {
delete process.env.OPENACP_CONFIG_PATH
delete process.env.OPENACP_TELEGRAM_BOT_TOKEN
delete process.env.OPENACP_TELEGRAM_CHAT_ID
delete process.env.OPENACP_DEFAULT_AGENT
delete process.env.OPENACP_RUN_MODE
delete process.env.OPENACP_API_PORT
delete process.env.OPENACP_LOG_LEVEL
delete process.env.OPENACP_LOG_DIR
delete process.env.OPENACP_DEBUG
delete process.env.OPENACP_TUNNEL_ENABLED
delete process.env.OPENACP_TUNNEL_PORT
delete process.env.OPENACP_TUNNEL_PROVIDER
fs.rmSync(tmpDir, { recursive: true, force: true })
})
const baseConfig = {
channels: { telegram: { enabled: false, botToken: 'test', chatId: 0 } },
defaultAgent: 'claude',
agents: {},
security: { allowedUserIds: [], maxConcurrentSessions: 20, sessionTimeoutMinutes: 60 },
}
it('overrides defaultAgent from env', async () => {
@ -157,6 +150,22 @@ describe('ConfigManager.applyEnvOverrides', () => {
expect(manager.get().defaultAgent).toBe('codex')
})
it('overrides Telegram bot token from env', async () => {
process.env.OPENACP_TELEGRAM_BOT_TOKEN = 'env-token'
const manager = createConfigAndManager(baseConfig)
await manager.load()
const telegram = manager.get().channels.telegram as any
expect(telegram.botToken).toBe('env-token')
})
it('overrides Telegram chat ID from env (as number)', async () => {
process.env.OPENACP_TELEGRAM_CHAT_ID = '123456789'
const manager = createConfigAndManager(baseConfig)
await manager.load()
const telegram = manager.get().channels.telegram as any
expect(telegram.chatId).toBe(123456789)
})
it('overrides runMode from env', async () => {
process.env.OPENACP_RUN_MODE = 'daemon'
const manager = createConfigAndManager(baseConfig)
@ -164,6 +173,13 @@ describe('ConfigManager.applyEnvOverrides', () => {
expect(manager.get().runMode).toBe('daemon')
})
it('overrides API port from env (as number)', async () => {
process.env.OPENACP_API_PORT = '9999'
const manager = createConfigAndManager(baseConfig)
await manager.load()
expect(manager.get().api.port).toBe(9999)
})
it('overrides log level from env', async () => {
process.env.OPENACP_LOG_LEVEL = 'debug'
const manager = createConfigAndManager(baseConfig)
@ -192,6 +208,27 @@ describe('ConfigManager.applyEnvOverrides', () => {
await manager.load()
expect(manager.get().logging.level).toBe('warn')
})
it('overrides tunnel enabled from env', async () => {
process.env.OPENACP_TUNNEL_ENABLED = 'true'
const manager = createConfigAndManager(baseConfig)
await manager.load()
expect(manager.get().tunnel.enabled).toBe(true)
})
it('overrides tunnel port from env', async () => {
process.env.OPENACP_TUNNEL_PORT = '4000'
const manager = createConfigAndManager(baseConfig)
await manager.load()
expect(manager.get().tunnel.port).toBe(4000)
})
it('overrides tunnel provider from env', async () => {
process.env.OPENACP_TUNNEL_PROVIDER = 'ngrok'
const manager = createConfigAndManager(baseConfig)
await manager.load()
expect(manager.get().tunnel.provider).toBe('ngrok')
})
})
describe('ConfigManager.save and hot-reload', () => {
@ -204,7 +241,10 @@ describe('ConfigManager.save and hot-reload', () => {
process.env.OPENACP_CONFIG_PATH = configPath
const config = {
channels: { telegram: { enabled: false, botToken: 'test', chatId: 0 } },
defaultAgent: 'claude',
agents: {},
security: { allowedUserIds: [], maxConcurrentSessions: 20, sessionTimeoutMinutes: 60 },
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2))
configManager = new ConfigManager()
@ -230,14 +270,14 @@ describe('ConfigManager.save and hot-reload', () => {
configManager.on('config:changed', (e) => events.push(e))
await configManager.save(
{ defaultAgent: 'codex' },
'defaultAgent',
{ security: { maxConcurrentSessions: 10 } },
'security.maxConcurrentSessions',
)
expect(events).toHaveLength(1)
expect(events[0]).toMatchObject({
path: 'defaultAgent',
value: 'codex',
path: 'security.maxConcurrentSessions',
value: 10,
})
})
@ -251,8 +291,9 @@ describe('ConfigManager.save and hot-reload', () => {
})
it('deep merges nested config', async () => {
await configManager.save({ workspace: { baseDir: '~/custom-workspace' } })
// Other workspace fields should still exist after deep merge
expect(configManager.get().workspace.baseDir).toBe('~/custom-workspace')
await configManager.save({ security: { maxConcurrentSessions: 5 } })
// Other security fields should still exist
expect(configManager.get().security.sessionTimeoutMinutes).toBe(60)
expect(configManager.get().security.maxConcurrentSessions).toBe(5)
})
})

View File

@ -3,7 +3,6 @@ import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { JsonFileSessionStore } from "../core/sessions/session-store.js";
import { SessionManager } from "../core/sessions/session-manager.js";
import type { SessionRecord } from "../core/types.js";
describe("Lazy Resume Integration", () => {
@ -89,72 +88,6 @@ describe("Lazy Resume Integration", () => {
store2.destroy();
});
// --- Regression tests for topicId persistence race condition ---
it("race condition: debounced patchRecord loses topicId on simulated crash", async () => {
// Reproduces the bug: createSession saves platform:{} immediately, then callers
// call patchRecord({ platform: { topicId } }) without immediate:true.
// If the server restarts before the 2-second debounce fires, topicId is lost.
const manager = new SessionManager(store);
// Step 1: initial save (no topicId — current createSession behavior when threadId not yet known)
await manager.patchRecord("sess-race", {
sessionId: "sess-race",
agentSessionId: "agent-1",
agentName: "claude",
workingDir: "/tmp",
channelId: "telegram",
status: "active",
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
name: "race-session",
platform: {},
}, { immediate: true });
// Step 2: caller sets topicId via a separate debounced patchRecord (current new-session.ts pattern)
await manager.patchRecord("sess-race", { platform: { topicId: 24952 } }); // no immediate!
// Simulate crash: destroy clears the debounce timer WITHOUT flushing to disk
store.destroy();
// After restart: reload from disk
const freshStore = new JsonFileSessionStore(filePath, 30);
const found = freshStore.findByPlatform("telegram", (p) => p.topicId === 24952);
expect(found).toBeUndefined(); // BUG: topicId was not persisted to disk
freshStore.destroy();
});
it("fix: topicId survives restart when included in the initial immediate save", async () => {
// After the fix: handleNewSession passes threadId into createSession, which includes
// platform.topicId in the initial patchRecord({ immediate: true }) call.
// No separate debounced patchRecord is needed.
const manager = new SessionManager(store);
// Fixed: topicId included in the initial immediate save
await manager.patchRecord("sess-fixed", {
sessionId: "sess-fixed",
agentSessionId: "agent-2",
agentName: "claude",
workingDir: "/tmp",
channelId: "telegram",
status: "active",
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
name: "fixed-session",
platform: { topicId: 24952 },
}, { immediate: true });
// Simulate crash
store.destroy();
// After restart
const freshStore = new JsonFileSessionStore(filePath, 30);
const found = freshStore.findByPlatform("telegram", (p) => p.topicId === 24952);
expect(found).toBeDefined(); // FIX: topicId survives
expect(found!.sessionId).toBe("sess-fixed");
freshStore.destroy();
});
it("platform data lookup matches by topicId", async () => {
await store.save({
sessionId: "s1",

View File

@ -43,7 +43,6 @@ vi.mock('../core/agents/agent-catalog.js', () => {
getInstalledAgent = vi.fn((_key: string) => undefined)
findRegistryAgent = vi.fn((_key: string) => null)
install = vi.fn().mockResolvedValue({ ok: true })
registerFallbackAgent = vi.fn()
getAvailable = vi.fn(() => [])
getInstalledEntries = vi.fn(() => ({
claude: { name: 'Claude Agent', command: 'npx', version: 'bundled', distribution: 'npx' },
@ -229,8 +228,14 @@ describe('runSetup integration', () => {
)
const written = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
// Channels are now managed by plugins, core config has empty channels
expect(written.channels).toEqual({})
// agents are now stored in agents.json, not config.json
expect(written.agents).toEqual({})
expect(written.defaultAgent).toBe('claude')
expect(written.workspace.baseDir).toBe('~/my-workspace')
expect(written.security.maxConcurrentSessions).toBe(20)
expect(written.security.sessionTimeoutMinutes).toBe(60)
// Built-in plugins were auto-registered
expect(mockPluginRegistry.save).toHaveBeenCalled()

View File

@ -90,7 +90,7 @@ const noInstanceCommands: Record<string, () => Promise<void>> = {
'-v': () => cmdVersion(args),
'update': () => cmdUpdate(args),
'adopt': () => cmdAdopt(args),
'instances': async () => cmdInstances(args, flags),
'instances': async () => cmdInstances(args),
'integrate': () => cmdIntegrate(args),
'dev': () => cmdDev(args),
}

View File

@ -1,85 +0,0 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("node:os", async () => {
const actual = await vi.importActual<typeof import("node:os")>("node:os");
return {
...actual,
homedir: () => process.env.OPENACP_TEST_HOME ?? actual.homedir(),
};
});
describe("integrate opencode plugin strategy", () => {
let tmpDir = "";
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openacp-integrate-test-"));
process.env.OPENACP_TEST_HOME = tmpDir;
});
afterEach(() => {
delete process.env.OPENACP_TEST_HOME;
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.resetModules();
vi.restoreAllMocks();
});
it("installs and uninstalls opencode handoff files", async () => {
const { getAgentCapabilities } = await import("../../core/agents/agent-dependencies.js");
const { installIntegration, uninstallIntegration, getIntegration } = await import("../integrate.js");
const caps = getAgentCapabilities("opencode");
expect(caps.integration?.strategy).toBe("plugin");
if (!caps.integration || caps.integration.strategy !== "plugin") {
throw new Error("Expected opencode plugin integration spec");
}
const installResult = await installIntegration("opencode", caps.integration);
expect(installResult.success).toBe(true);
const commandPath = path.join(tmpDir, ".config", "opencode", "commands", "openacp-handoff.md");
const pluginPath = path.join(tmpDir, ".config", "opencode", "plugins", "openacp-handoff.js");
expect(fs.existsSync(commandPath)).toBe(true);
expect(fs.existsSync(pluginPath)).toBe(true);
const commandContent = fs.readFileSync(commandPath, "utf-8");
expect(commandContent).toContain("name: openacp:handoff");
const pluginContent = fs.readFileSync(pluginPath, "utf-8");
expect(pluginContent).toContain("OPENCODE_SESSION_ID");
expect(pluginContent).toContain("id: \"openacp-session-inject\"");
expect(pluginContent).toContain("sessionID: input.sessionID");
expect(pluginContent).toContain("messageID: \"openacp-inject\"");
const reinstallResult = await installIntegration("opencode", caps.integration);
expect(reinstallResult.success).toBe(true);
expect(reinstallResult.logs).toContain("Already installed, skipping.");
const integration = getIntegration("opencode");
expect(integration).toBeDefined();
expect(integration!.items.map((item) => item.id)).toEqual(["handoff"]);
expect(integration!.items[0]!.isInstalled()).toBe(true);
const uninstallResult = await uninstallIntegration("opencode", caps.integration);
expect(uninstallResult.success).toBe(true);
expect(fs.existsSync(commandPath)).toBe(false);
expect(fs.existsSync(pluginPath)).toBe(false);
expect(integration!.items[0]!.isInstalled()).toBe(false);
});
it("returns success with a message when uninstalling missing files", async () => {
const { getAgentCapabilities } = await import("../../core/agents/agent-dependencies.js");
const { uninstallIntegration } = await import("../integrate.js");
const caps = getAgentCapabilities("opencode");
expect(caps.integration?.strategy).toBe("plugin");
if (!caps.integration || caps.integration.strategy !== "plugin") {
throw new Error("Expected opencode plugin integration spec");
}
const uninstallResult = await uninstallIntegration("opencode", caps.integration);
expect(uninstallResult.success).toBe(true);
expect(uninstallResult.logs).toContain("Nothing to remove.");
});
});

View File

@ -2,25 +2,6 @@ import { readApiPort, removeStalePortFile, apiCall } from '../api-client.js'
import { wantsHelp } from './helpers.js'
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
/**
* Extract a human-readable error message from an API response body.
*
* The API can return errors in two shapes:
* - Structured: `{ error: { message: "...", code: "...", statusCode: N } }` (from globalErrorHandler)
* - Plain string: `{ error: "..." }` (from inline reply.send())
*
* Without this helper, `String(data.error)` produces "[object Object]" for structured errors.
*/
function extractApiError(data: Record<string, unknown>, fallback = 'API request failed'): string {
const err = data.error
if (!err) return fallback
if (typeof err === 'string') return err
if (typeof err === 'object' && err !== null && 'message' in err) {
return String((err as Record<string, unknown>).message)
}
return fallback
}
function printApiHelp(): void {
console.log(`
\x1b[1mopenacp api\x1b[0m — Interact with the running OpenACP daemon
@ -324,8 +305,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -349,8 +330,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess({ cancelled: true, sessionId })
@ -416,8 +397,8 @@ Shows the version of the currently running daemon process.
process.exit(1)
}
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -465,8 +446,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -482,8 +463,8 @@ Shows the version of the currently running daemon process.
const res = await call(`/api/sessions/${encodeURIComponent(sessionId)}`)
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -521,8 +502,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -533,8 +514,8 @@ Shows the version of the currently running daemon process.
const res = await call('/api/health')
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -560,8 +541,8 @@ Shows the version of the currently running daemon process.
const res = await call('/api/restart', { method: 'POST' })
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess({ restarted: true })
@ -574,8 +555,8 @@ Shows the version of the currently running daemon process.
const res = await call('/api/config')
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -601,8 +582,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -636,8 +617,8 @@ Shows the version of the currently running daemon process.
const res = await call('/api/tunnel')
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -662,8 +643,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess({ sent: true })
@ -673,8 +654,8 @@ Shows the version of the currently running daemon process.
const res = await call('/api/version')
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -694,8 +675,8 @@ Shows the version of the currently running daemon process.
const res = await call(`/api/sessions/${encodeURIComponent(sessionId)}/config`)
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -742,8 +723,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -759,8 +740,8 @@ Shows the version of the currently running daemon process.
const res = await call(`/api/sessions/${encodeURIComponent(sessionId)}/config/overrides`)
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -790,8 +771,8 @@ Shows the version of the currently running daemon process.
})
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)
@ -802,8 +783,8 @@ Shows the version of the currently running daemon process.
const res = await call(`/api/sessions/${encodeURIComponent(sessionId)}/config/overrides`)
const data = await res.json() as Record<string, unknown>
if (!res.ok) {
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
console.error(`Error: ${extractApiError(data)}`)
if (json) jsonError(ErrorCodes.API_ERROR, String(data.error ?? 'API request failed'))
console.error(`Error: ${data.error}`)
process.exit(1)
}
if (json) jsonSuccess(data)

View File

@ -87,7 +87,7 @@ export async function cmdDefault(command: string | undefined, instanceRoot?: str
const portStr = fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()
port = parseInt(portStr) || null
} catch {
port = 21420
port = config.api.port ?? null
}
jsonSuccess({
pid: result.pid,
@ -124,7 +124,7 @@ export async function cmdDefault(command: string | undefined, instanceRoot?: str
const portStr = fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()
port = parseInt(portStr) || null
} catch {
port = 21420
port = config.api.port ?? null
}
jsonSuccess({
pid: process.pid,

View File

@ -57,14 +57,6 @@ Connect messaging platforms (Telegram, Discord) to 28+ AI coding agents via ACP
openacp integrate <agent> --uninstall
openacp adopt <agent> <id> Adopt an external session \x1b[2m[--json]\x1b[0m
\x1b[1mRemote Access:\x1b[0m
openacp remote Generate one-time remote access link \x1b[2m[--json]\x1b[0m
openacp remote --role admin Specify role: admin (default) or viewer
openacp remote --expire 48h Set expiry duration (default: 24h)
openacp remote --no-tunnel Local link only (skip tunnel URL)
openacp remote --no-qr Skip QR code output
openacp remote --name <label> Custom token name
\x1b[1mTunnels:\x1b[0m
openacp tunnel add <port> [--label name] Create tunnel to local port \x1b[2m[--json]\x1b[0m
openacp tunnel list List active tunnels \x1b[2m[--json]\x1b[0m

View File

@ -20,7 +20,7 @@ export async function cmdInstall(args: string[], instanceRoot?: string): Promise
openacp install <package>
\x1b[1mArguments:\x1b[0m
<package> npm package name (e.g. @openacp/discord-adapter)
<package> npm package name (e.g. @openacp/adapter-discord)
Installs the plugin to ~/.openacp/plugins/.
@ -29,7 +29,7 @@ Installs the plugin to ~/.openacp/plugins/.
-h, --help Show this help message
\x1b[1mExamples:\x1b[0m
openacp install @openacp/discord-adapter
openacp install @openacp/adapter-discord
`)
return
}

View File

@ -33,7 +33,7 @@ export async function buildInstanceListEntries(): Promise<InstanceListEntry[]> {
})
}
export async function cmdInstances(args: string[] = [], parentFlags?: { dir?: string; from?: string; name?: string }): Promise<void> {
export async function cmdInstances(args: string[] = []): Promise<void> {
if (wantsHelp(args)) {
printInstancesHelp()
return
@ -42,13 +42,6 @@ export async function cmdInstances(args: string[] = [], parentFlags?: { dir?: st
const sub = args[0]
const subArgs = args.slice(1)
// Re-inject flags that were consumed by top-level parser
if (parentFlags) {
if (parentFlags.dir && !subArgs.includes('--dir')) subArgs.push('--dir', parentFlags.dir)
if (parentFlags.from && !subArgs.includes('--from')) subArgs.push('--from', parentFlags.from)
if (parentFlags.name && !subArgs.includes('--name')) subArgs.push('--name', parentFlags.name)
}
if (!sub || sub === 'list') return cmdInstancesList(subArgs)
if (sub === 'create') return cmdInstancesCreate(subArgs)
@ -164,39 +157,25 @@ export async function cmdInstancesCreate(args: string[]): Promise<void> {
fs.mkdirSync(instanceRoot, { recursive: true })
const { copyInstance } = await import('../../core/instance/instance-copy.js')
await copyInstance(fromRoot, instanceRoot, {})
// Update config for new instance: name + workspace dir
// Write instanceName into config
const configPath = path.join(instanceRoot, 'config.json')
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
config.instanceName = name
if (!config.workspace) config.workspace = {}
config.workspace.baseDir = resolvedDir
fs.writeFileSync(configPath, JSON.stringify(config, null, 2))
} catch {}
} else if (noInteractive || !process.stdin.isTTY) {
// Minimal config for non-interactive mode
fs.mkdirSync(instanceRoot, { recursive: true })
const config: Record<string, unknown> = {
channels: { sse: { enabled: true } },
defaultAgent: agent || 'claude',
workspace: { baseDir: resolvedDir },
runMode: 'daemon',
autoStart: false,
instanceName: name,
}
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 {
// Interactive wizard — requires plugin system; fall back to minimal config
fs.mkdirSync(instanceRoot, { recursive: true })
const config: Record<string, unknown> = {
channels: { sse: { enabled: true } },
defaultAgent: agent || 'claude',
workspace: { baseDir: resolvedDir },
runMode: 'daemon',
autoStart: false,
instanceName: name,
}
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))
console.log(`Instance created at ${resolvedDir}. Run 'openacp setup' inside that directory to configure it.`)

View File

@ -17,12 +17,11 @@ export async function cmdIntegrate(args: string[]): Promise<void> {
-h, --help Show this help message
Integrations enable features like session handoff from an agent
to OpenACP (Telegram/Discord). For example, integrations add an
agent-native handoff command such as /openacp:handoff.
to OpenACP (Telegram/Discord). For example, the Claude integration adds
a "Handoff" slash command to Claude Code.
\x1b[1mExamples:\x1b[0m
openacp integrate claude
openacp integrate opencode
openacp integrate claude --uninstall
`)
return

View File

@ -16,158 +16,63 @@ import {
generatePluginGuide,
} from '../plugin-template/index.js'
const VALID_LICENSES = ['MIT', 'Apache-2.0', 'ISC', 'UNLICENSED']
const NAME_REGEX = /^(@[a-z0-9-]+\/)?[a-z0-9-]+$/
export async function cmdPluginCreate(): Promise<void> {
p.intro('Create a new OpenACP plugin')
function parseCreateArgs(args: string[]): { name?: string; description?: string; author?: string; license?: string; dir?: string } {
const parsed: Record<string, string> = {}
for (let i = 0; i < args.length; i++) {
const arg = args[i]
const next = args[i + 1]
if ((arg === '--name' || arg === '-n') && next) { parsed.name = next; i++ }
else if ((arg === '--description' || arg === '-d') && next) { parsed.description = next; i++ }
else if ((arg === '--author' || arg === '-a') && next) { parsed.author = next; i++ }
else if ((arg === '--license' || arg === '-l') && next) { parsed.license = next; i++ }
else if ((arg === '--output' || arg === '-o') && next) { parsed.dir = next; i++ }
else if (!arg.startsWith('-') && !parsed.name) { parsed.name = arg } // positional: first non-flag = name
}
return parsed
}
/**
* Re-extract --name from process.argv for plugin create, since the top-level
* extractInstanceFlags() consumes --name as an instance flag.
*/
function recoverNameFromProcessArgs(): string | undefined {
const argv = process.argv
for (let i = 0; i < argv.length; i++) {
if (argv[i] === 'create') {
// Look for --name or -n after 'create'
for (let j = i + 1; j < argv.length; j++) {
if ((argv[j] === '--name' || argv[j] === '-n') && argv[j + 1]) return argv[j + 1]
if (!argv[j]!.startsWith('-') && j === i + 1) return argv[j] // positional right after create
}
}
}
return undefined
}
export async function cmdPluginCreate(args: string[] = []): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
console.log(`
\x1b[1mopenacp plugin create\x1b[0m — Scaffold a new plugin project
\x1b[1mUsage:\x1b[0m
openacp plugin create Interactive mode
openacp plugin create --name <name> [options] Non-interactive mode
\x1b[1mOptions:\x1b[0m
-n, --name <name> Plugin name (e.g., @myorg/my-plugin) [required]
-d, --description <desc> Short description
-a, --author <author> Author name and email
-l, --license <license> License: MIT, Apache-2.0, ISC, UNLICENSED (default: MIT)
-o, --output <path> Target directory (default: ./<plugin-name>)
-h, --help Show this help message
\x1b[1mExamples:\x1b[0m
openacp plugin create
openacp plugin create --name @myorg/my-plugin --description "My plugin" --license MIT
openacp plugin create -n my-plugin -d "My plugin" -o ./plugins/my-plugin
`)
return
}
const cliArgs = parseCreateArgs(args)
// --name is consumed by top-level extractInstanceFlags(), recover from process.argv
if (!cliArgs.name) cliArgs.name = recoverNameFromProcessArgs()
let pluginName: string
let description: string
let author: string
let license: string
if (cliArgs.name) {
// Non-interactive: validate provided args, prompt only for missing required fields
if (!NAME_REGEX.test(cliArgs.name)) {
console.error('Error: invalid plugin name. Must be a valid npm package name (lowercase, hyphens, optional @scope/)')
process.exit(1)
}
if (cliArgs.license && !VALID_LICENSES.includes(cliArgs.license)) {
console.error(`Error: invalid license. Must be one of: ${VALID_LICENSES.join(', ')}`)
process.exit(1)
}
pluginName = cliArgs.name
description = cliArgs.description ?? ''
author = cliArgs.author ?? ''
license = cliArgs.license ?? 'MIT'
} else {
// Interactive mode
p.intro('Create a new OpenACP plugin')
const result = await p.group(
{
name: () =>
p.text({
message: 'Plugin name (e.g., @myorg/adapter-matrix)',
placeholder: '@myorg/my-plugin',
validate: (value: string | undefined) => {
if (!value || !value.trim()) return 'Plugin name is required'
if (!NAME_REGEX.test(value.trim())) {
return 'Must be a valid npm package name (lowercase, hyphens, optional @scope/)'
}
return undefined
},
}),
description: () =>
p.text({
message: 'Description',
placeholder: 'A short description of your plugin',
}),
author: () =>
p.text({
message: 'Author',
placeholder: 'Your Name <email@example.com>',
}),
license: () =>
p.select({
message: 'License',
options: [
{ value: 'MIT', label: 'MIT' },
{ value: 'Apache-2.0', label: 'Apache 2.0' },
{ value: 'ISC', label: 'ISC' },
{ value: 'UNLICENSED', label: 'Unlicensed (private)' },
],
}),
const result = await p.group(
{
name: () =>
p.text({
message: 'Plugin name (e.g., @myorg/adapter-matrix)',
placeholder: '@myorg/my-plugin',
validate: (value: string | undefined) => {
if (!value || !value.trim()) return 'Plugin name is required'
if (!/^(@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(value.trim())) {
return 'Must be a valid npm package name (lowercase, hyphens, optional @scope/)'
}
return undefined
},
}),
description: () =>
p.text({
message: 'Description',
placeholder: 'A short description of your plugin',
}),
author: () =>
p.text({
message: 'Author',
placeholder: 'Your Name <email@example.com>',
}),
license: () =>
p.select({
message: 'License',
options: [
{ value: 'MIT', label: 'MIT' },
{ value: 'Apache-2.0', label: 'Apache 2.0' },
{ value: 'ISC', label: 'ISC' },
{ value: 'UNLICENSED', label: 'Unlicensed (private)' },
],
}),
},
{
onCancel: () => {
p.cancel('Plugin creation cancelled.')
process.exit(0)
},
{
onCancel: () => {
p.cancel('Plugin creation cancelled.')
process.exit(0)
},
},
)
},
)
pluginName = (result.name as string).trim()
description = (result.description as string) || ''
author = (result.author as string) || ''
license = result.license as string
}
const isInteractive = !cliArgs.name
const pluginName = result.name.trim()
const dirName = pluginName.replace(/^@[^/]+\//, '') // strip scope for directory name
const targetDir = cliArgs.dir ? path.resolve(process.cwd(), cliArgs.dir) : path.resolve(process.cwd(), dirName)
const targetDir = path.resolve(process.cwd(), dirName)
if (fs.existsSync(targetDir)) {
if (isInteractive) {
p.cancel(`Directory "${cliArgs.dir ?? dirName}" already exists.`)
} else {
console.error(`Error: directory "${cliArgs.dir ?? dirName}" already exists.`)
}
p.cancel(`Directory "${dirName}" already exists.`)
process.exit(1)
}
const spinner = isInteractive ? p.spinner() : null
if (spinner) spinner.start('Scaffolding plugin...')
const spinner = p.spinner()
spinner.start('Scaffolding plugin...')
// Create directory structure
fs.mkdirSync(path.join(targetDir, 'src', '__tests__'), { recursive: true })
@ -175,9 +80,9 @@ export async function cmdPluginCreate(args: string[] = []): Promise<void> {
// Collect template params
const params: TemplateParams = {
pluginName,
description,
author,
license,
description: (result.description as string) || '',
author: (result.author as string) || '',
license: result.license as string,
cliVersion: getCurrentVersion(),
}
@ -199,26 +104,20 @@ export async function cmdPluginCreate(args: string[] = []): Promise<void> {
fs.writeFileSync(path.join(targetDir, file.relativePath), file.content)
}
if (spinner) {
spinner.stop('Plugin scaffolded!')
}
spinner.stop('Plugin scaffolded!')
const displayDir = cliArgs.dir ?? `./${dirName}`
if (isInteractive) {
p.note(
[
`cd ${displayDir}`,
'npm install',
'npm run build',
'npm test',
'',
'# Start development with hot-reload:',
`openacp dev .`,
].join('\n'),
'Next steps',
)
p.outro(`Plugin ${pluginName} created in ${displayDir}`)
} else {
console.log(`✅ Plugin ${pluginName} created in ${displayDir}`)
}
p.note(
[
`cd ${dirName}`,
'npm install',
'npm run build',
'npm test',
'',
'# Start development with hot-reload:',
`openacp dev .`,
].join('\n'),
'Next steps',
)
p.outro(`Plugin ${pluginName} created in ./${dirName}`)
}

View File

@ -71,7 +71,7 @@ Shows all plugins registered in the plugin registry.
export async function cmdPlugin(args: string[] = [], instanceRoot?: string): Promise<void> {
const subcommand = args[0]
if (!subcommand || (wantsHelp(args) && !['create', 'search'].includes(subcommand))) {
if (wantsHelp(args) || !subcommand) {
console.log(`
\x1b[1mopenacp plugin\x1b[0m — Plugin management
@ -86,8 +86,7 @@ export async function cmdPlugin(args: string[] = [], instanceRoot?: string): Pro
openacp plugin enable <name> Enable a plugin
openacp plugin disable <name> Disable a plugin
openacp plugin configure <name> Run interactive configuration
openacp plugin create Scaffold a new plugin project (interactive)
openacp plugin create --name <name> Scaffold a new plugin project (non-interactive)
openacp plugin create Scaffold a new plugin project
\x1b[1mOptions:\x1b[0m
--json Output result as JSON
@ -96,12 +95,12 @@ export async function cmdPlugin(args: string[] = [], instanceRoot?: string): Pro
\x1b[1mExamples:\x1b[0m
openacp plugin list
openacp plugin search telegram
openacp plugin add @openacp/discord-adapter
openacp plugin add @openacp/adapter-discord
openacp plugin add translator@1.2.0
openacp plugin add ./my-plugin Install from local directory
openacp plugin enable @openacp/discord-adapter
openacp plugin configure @openacp/discord-adapter
openacp plugin remove @openacp/discord-adapter --purge
openacp plugin enable @openacp/adapter-discord
openacp plugin configure @openacp/adapter-discord
openacp plugin remove @openacp/adapter-discord --purge
`)
return
}
@ -175,7 +174,7 @@ export async function cmdPlugin(args: string[] = [], instanceRoot?: string): Pro
case 'create': {
const { cmdPluginCreate } = await import('./plugin-create.js')
await cmdPluginCreate(args.slice(1))
await cmdPluginCreate()
return
}

View File

@ -47,13 +47,12 @@ Stops the running daemon (if any) and starts a new one.
const pidPath = getPidPath(root)
// Stop existing daemon (ignore errors — it may not be running)
if (!json) console.log('Stopping...')
const stopResult = await stopDaemon(pidPath, root)
if (!json && stopResult.stopped) {
if (stopResult.stopped) {
console.log(`Stopped daemon (was PID ${stopResult.pid})`)
}
const cm = new ConfigManager(path.join(root, 'config.json'))
const cm = new ConfigManager()
if (!(await cm.exists())) {
if (json) jsonError(ErrorCodes.CONFIG_NOT_FOUND, 'No config found. Run "openacp" first to set up.')
console.error('No config found. Run "openacp" first to set up.')
@ -63,13 +62,8 @@ Stops the running daemon (if any) and starts a new one.
await cm.load()
const config = cm.get()
// Determine mode: explicit flag > was-running-as-daemon > config
// If a daemon was running (PID exists), restart as daemon to preserve the current mode.
// `openacp start` always starts as daemon regardless of config.runMode, so we must not
// use config.runMode alone — otherwise a daemon started via `openacp start` with
// runMode:'foreground' would incorrectly restart in foreground.
const hadDaemon = stopResult.pid !== undefined
const useForeground = json ? false : (forceForeground || (!forceDaemon && !hadDaemon && config.runMode !== 'daemon'))
// Determine mode: explicit flag > config; --json always uses daemon mode
const useForeground = json ? false : (forceForeground || (!forceDaemon && config.runMode !== 'daemon'))
if (useForeground) {
markRunning(root)

View File

@ -64,7 +64,7 @@ Requires an existing config — run 'openacp' first to set up.
port = parseInt(portStr) || null
} catch {
// Fall back to configured port
port = 21420
port = config.api.port ?? null
}
jsonSuccess({
pid: result.pid,

View File

@ -167,14 +167,10 @@ export function readInstanceInfo(root: string): InstanceInfo {
// Read enabled channels from plugins.json
try {
const plugins = JSON.parse(fs.readFileSync(path.join(root, 'plugins.json'), 'utf-8'))
const adapterMap: Array<{ pluginName: string; channelId: string }> = [
{ pluginName: '@openacp/telegram', channelId: 'telegram' },
{ pluginName: '@openacp/discord-adapter', channelId: 'discord' },
{ pluginName: '@openacp/slack-adapter', channelId: 'slack' },
]
for (const { pluginName, channelId } of adapterMap) {
if (plugins.installed?.[pluginName] && plugins.installed[pluginName].enabled !== false) {
result.channels.push(channelId)
const adapters = ['@openacp/telegram', '@openacp/discord', '@openacp/slack']
for (const name of adapters) {
if (plugins.installed?.[name] && plugins.installed[name].enabled !== false) {
result.channels.push(name.replace('@openacp/', ''))
}
}
} catch {}

View File

@ -27,7 +27,7 @@ export async function cmdUninstall(args: string[], instanceRoot?: string): Promi
-h, --help Show this help message
\x1b[1mExamples:\x1b[0m
openacp uninstall @openacp/discord-adapter
openacp uninstall @openacp/adapter-discord
`)
return
}

View File

@ -2,11 +2,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, chmodSy
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { getAgentCapabilities, commandExists, listAgentsWithIntegration } from "../core/agents/agent-dependencies.js";
import type {
AgentIntegrationSpec,
AgentHooksIntegrationSpec,
AgentPluginIntegrationSpec,
} from "../core/agents/agent-dependencies.js";
import type { AgentIntegrationSpec } from "../core/agents/agent-dependencies.js";
export interface IntegrationResult {
success: boolean;
@ -28,21 +24,13 @@ export interface AgentIntegration {
const HOOK_MARKER = "openacp-inject-session.sh";
function isPluginIntegrationSpec(spec: AgentIntegrationSpec): spec is AgentPluginIntegrationSpec {
return spec.strategy === "plugin";
}
function isHooksIntegrationSpec(spec: AgentIntegrationSpec): spec is AgentHooksIntegrationSpec {
return spec.strategy === "hooks";
}
function expandPath(p: string): string {
return p.replace(/^~/, homedir());
}
// --- Script generators ---
function generateInjectScript(_agentKey: string, spec: AgentHooksIntegrationSpec): string {
function generateInjectScript(_agentKey: string, spec: AgentIntegrationSpec): string {
const sidVar = spec.sessionIdVar ?? "SESSION_ID";
const cwdVar = spec.workingDirVar ?? "WORKING_DIR";
@ -143,7 +131,7 @@ User: "I want to see this React app on my phone"
`;
}
function generateHandoffCommand(_agentKey: string, spec: AgentHooksIntegrationSpec): string {
function generateHandoffCommand(_agentKey: string, spec: AgentIntegrationSpec): string {
const sidVar = spec.sessionIdVar ?? "SESSION_ID";
const cwdVar = spec.workingDirVar ?? "WORKING_DIR";
const hooksDir = expandPath(spec.hooksDirPath);
@ -166,44 +154,6 @@ Examples:
`;
}
function generateOpencodeHandoffCommand(spec: AgentPluginIntegrationSpec): string {
return `---
name: ${spec.handoffCommandName}
description: Transfer current OpenCode session to OpenACP (Telegram/Discord)
---
Use OPENCODE_SESSION_ID from injected context, then run:
openacp adopt opencode <OPENCODE_SESSION_ID>
If a channel argument is provided, append:
--channel <channel_name>
Usage:
/${spec.handoffCommandName}
/${spec.handoffCommandName} telegram
`;
}
function generateOpencodePlugin(spec: AgentPluginIntegrationSpec): string {
return `export const OpenACPHandoffPlugin = async () => {
return {
"command.execute.before": async (input, output) => {
if (input.command !== ${JSON.stringify(spec.handoffCommandName)}) return
output.parts.unshift({
id: "openacp-session-inject",
sessionID: input.sessionID,
messageID: "openacp-inject",
type: "text",
text: \`OPENCODE_SESSION_ID: \${input.sessionID}\\n\`,
})
},
}
}
`;
}
// --- Settings mergers ---
function mergeSettingsJson(settingsPath: string, hookEvent: string, hookScriptPath: string): void {
@ -304,7 +254,7 @@ function removeFromHooksJson(settingsPath: string, hookEvent: string): void {
// --- Core install/uninstall ---
async function installHooksIntegration(agentKey: string, spec: AgentHooksIntegrationSpec): Promise<IntegrationResult> {
export async function installIntegration(agentKey: string, spec: AgentIntegrationSpec): Promise<IntegrationResult> {
const logs: string[] = [];
try {
// Check jq
@ -363,7 +313,7 @@ async function installHooksIntegration(agentKey: string, spec: AgentHooksIntegra
}
}
async function uninstallHooksIntegration(agentKey: string, spec: AgentHooksIntegrationSpec): Promise<IntegrationResult> {
export async function uninstallIntegration(agentKey: string, spec: AgentIntegrationSpec): Promise<IntegrationResult> {
const logs: string[] = [];
try {
const hooksDir = expandPath(spec.hooksDirPath);
@ -411,107 +361,26 @@ async function uninstallHooksIntegration(agentKey: string, spec: AgentHooksInteg
}
}
async function installPluginIntegration(_agentKey: string, spec: AgentPluginIntegrationSpec): Promise<IntegrationResult> {
const logs: string[] = [];
try {
const commandsDir = expandPath(spec.commandsPath);
mkdirSync(commandsDir, { recursive: true });
const commandPath = join(commandsDir, spec.handoffCommandFile);
const pluginsDir = expandPath(spec.pluginsPath);
mkdirSync(pluginsDir, { recursive: true });
const pluginPath = join(pluginsDir, spec.pluginFileName);
if (existsSync(commandPath) && existsSync(pluginPath)) {
logs.push("Already installed, skipping.");
return { success: true, logs };
}
if (existsSync(commandPath) || existsSync(pluginPath)) {
logs.push("Overwriting existing files.");
}
writeFileSync(commandPath, generateOpencodeHandoffCommand(spec));
logs.push(`Created ${commandPath}`);
writeFileSync(pluginPath, generateOpencodePlugin(spec));
logs.push(`Created ${pluginPath}`);
return { success: true, logs };
} catch (err) {
logs.push(`Error: ${err instanceof Error ? err.message : String(err)}`);
return { success: false, logs };
}
}
async function uninstallPluginIntegration(_agentKey: string, spec: AgentPluginIntegrationSpec): Promise<IntegrationResult> {
const logs: string[] = [];
try {
const commandPath = join(expandPath(spec.commandsPath), spec.handoffCommandFile);
let removedCount = 0;
if (existsSync(commandPath)) {
unlinkSync(commandPath);
logs.push(`Removed ${commandPath}`);
removedCount += 1;
}
const pluginPath = join(expandPath(spec.pluginsPath), spec.pluginFileName);
if (existsSync(pluginPath)) {
unlinkSync(pluginPath);
logs.push(`Removed ${pluginPath}`);
removedCount += 1;
}
if (removedCount === 0) {
logs.push("Nothing to remove.");
}
return { success: true, logs };
} catch (err) {
logs.push(`Error: ${err instanceof Error ? err.message : String(err)}`);
return { success: false, logs };
}
}
export async function installIntegration(agentKey: string, spec: AgentIntegrationSpec): Promise<IntegrationResult> {
if (isHooksIntegrationSpec(spec)) {
return installHooksIntegration(agentKey, spec);
}
return installPluginIntegration(agentKey, spec);
}
export async function uninstallIntegration(agentKey: string, spec: AgentIntegrationSpec): Promise<IntegrationResult> {
if (isHooksIntegrationSpec(spec)) {
return uninstallHooksIntegration(agentKey, spec);
}
return uninstallPluginIntegration(agentKey, spec);
}
// --- Public API (backward compat with existing cmdIntegrate / Telegram integrate) ---
function buildHandoffItem(agentKey: string, spec: AgentIntegrationSpec): IntegrationItem {
const hooksDir = expandPath(spec.hooksDirPath);
return {
id: "handoff",
name: "Handoff",
description: "Transfer sessions between terminal and messaging platforms",
isInstalled(): boolean {
if (isHooksIntegrationSpec(spec)) {
const hooksDir = expandPath(spec.hooksDirPath);
return (
existsSync(join(hooksDir, "openacp-inject-session.sh")) &&
existsSync(join(hooksDir, "openacp-handoff.sh"))
);
}
const commandPath = join(expandPath(spec.commandsPath), spec.handoffCommandFile);
const pluginPath = join(expandPath(spec.pluginsPath), spec.pluginFileName);
return existsSync(commandPath) && existsSync(pluginPath);
return (
existsSync(join(hooksDir, "openacp-inject-session.sh")) &&
existsSync(join(hooksDir, "openacp-handoff.sh"))
);
},
install: () => installIntegration(agentKey, spec),
uninstall: () => uninstallIntegration(agentKey, spec),
};
}
function getSkillBasePath(spec: AgentHooksIntegrationSpec): string {
function getSkillBasePath(spec: AgentIntegrationSpec): string {
// Skills go into the agent's skills directory (sibling to commands)
// Claude: ~/.claude/skills/, Cursor: ~/.cursor/skills/
const base = spec.commandsPath!;
@ -521,11 +390,10 @@ function getSkillBasePath(spec: AgentHooksIntegrationSpec): string {
}
function buildTunnelItem(spec: AgentIntegrationSpec): IntegrationItem | null {
if (!isHooksIntegrationSpec(spec) || !spec.commandsPath) return null;
const hooksSpec = spec;
if (!spec.commandsPath) return null;
function getTunnelPath(): string {
return join(getSkillBasePath(hooksSpec), "openacp-tunnel", "SKILL.md");
return join(getSkillBasePath(spec), "openacp-tunnel", "SKILL.md");
}
return {

View File

@ -188,6 +188,7 @@ interface InstallContext {
pluginName: string
terminal: TerminalIO // text, select, confirm, password, multiselect, log, spinner, note
settings: SettingsAPI
legacyConfig?: Record<string, unknown>
dataDir: string
log: Logger
}
@ -223,7 +224,7 @@ Declare in \`permissions\` array. Only request what you need.
Calling a method without the required permission throws \`PluginPermissionError\`.
## Middleware Hooks (19 total)
## Middleware Hooks (20 total)
Register with \`ctx.registerMiddleware(hook, { priority?, handler })\`. Return \`null\` to block the flow, call \`next()\` to continue.

View File

@ -10,37 +10,27 @@ const log = createChildLogger({ module: "post-upgrade" });
* Silent if everything is OK.
*/
export async function runPostUpgradeChecks(config: Config): Promise<void> {
// 1. Tunnel provider binary — read from plugin settings (tunnel migrated out of config.json)
try {
const { SettingsManager } = await import("../core/plugin/settings-manager.js");
const sm = new SettingsManager(config.workspace?.baseDir ?? "~/.openacp/plugins/data");
const tunnelSettings = await sm.loadSettings("@openacp/tunnel");
const tunnelEnabled = (tunnelSettings.enabled as boolean) ?? false;
const tunnelProvider = (tunnelSettings.provider as string) ?? "cloudflare";
if (tunnelEnabled) {
if (tunnelProvider === "cloudflare") {
try {
const { ensureCloudflared } = await import(
"../plugins/tunnel/providers/install-cloudflared.js"
);
await ensureCloudflared();
} catch (err) {
log.warn(
{ err: (err as Error).message },
"Could not install cloudflared. Tunnel may not work.",
);
}
} else {
if (!commandExists(tunnelProvider)) {
log.warn(
`Tunnel provider "${tunnelProvider}" is not installed. Install it or switch to cloudflare (free, auto-installed).`,
);
}
// 1. Tunnel provider binary
if (config.tunnel.enabled) {
if (config.tunnel.provider === "cloudflare") {
try {
const { ensureCloudflared } = await import(
"../plugins/tunnel/providers/install-cloudflared.js"
);
await ensureCloudflared();
} catch (err) {
log.warn(
{ err: (err as Error).message },
"Could not install cloudflared. Tunnel may not work.",
);
}
} else {
if (!commandExists(config.tunnel.provider)) {
log.warn(
`Tunnel provider "${config.tunnel.provider}" is not installed. Install it or switch to cloudflare (free, auto-installed).`,
);
}
}
} catch {
// tunnel settings not available — skip tunnel check
}
// 2. Claude CLI integration + jq

View File

@ -72,7 +72,7 @@ export async function runUpdate(): Promise<boolean> {
}
export async function checkAndPromptUpdate(): Promise<void> {
if (process.env.OPENACP_DEV_LOOP || process.env.OPENACP_SKIP_UPDATE_CHECK || !process.stdin.isTTY) return
if (process.env.OPENACP_DEV_LOOP || process.env.OPENACP_SKIP_UPDATE_CHECK) return
const current = getCurrentVersion()
if (current === '0.0.0-dev') return

View File

@ -1,154 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { AgentSwitchHandler } from '../agent-switch-handler.js';
import { Session } from '../sessions/session.js';
import { TypedEmitter } from '../utils/typed-emitter.js';
import type { AgentEvent } from '../types.js';
vi.mock('../agents/agent-registry.js', () => ({
getAgentCapabilities: () => ({ supportsResume: true }),
}));
function mockAgentInstance(id = 'agent-1') {
const emitter = new TypedEmitter<{ agent_event: (event: AgentEvent) => void }>();
return Object.assign(emitter, {
sessionId: id,
prompt: vi.fn().mockResolvedValue(undefined),
cancel: vi.fn().mockResolvedValue(undefined),
destroy: vi.fn().mockResolvedValue(undefined),
onPermissionRequest: vi.fn(),
promptCapabilities: {},
initialSessionResponse: undefined,
agentCapabilities: undefined,
addAllowedPath: vi.fn(),
}) as any;
}
function makeSession(agentName = 'claude') {
const session = new Session({
channelId: 'telegram',
agentName,
workingDirectory: '/workspace',
agentInstance: mockAgentInstance(),
});
return session;
}
function makeDeps(sessionOverride?: Session) {
const session = sessionOverride ?? makeSession();
const newAgentInstance = mockAgentInstance('new-agent');
const resumedAgentInstance = mockAgentInstance('resumed-agent');
const sessionManager = {
getSession: vi.fn().mockReturnValue(session),
patchRecord: vi.fn().mockResolvedValue(undefined),
};
const agentManager = {
getAgent: vi.fn().mockReturnValue({ name: 'gemini' }),
spawn: vi.fn().mockResolvedValue(newAgentInstance),
resume: vi.fn().mockResolvedValue(resumedAgentInstance),
};
const contextService = {
flushSession: vi.fn().mockResolvedValue(undefined),
buildContext: vi.fn().mockResolvedValue({ markdown: '# History\n\nTurn 1' }),
};
const deps = {
sessionManager,
agentManager,
configManager: { get: vi.fn().mockReturnValue({ agentSwitch: { labelHistory: true } }) },
eventBus: { emit: vi.fn() },
adapters: new Map(),
bridges: new Map(),
createBridge: vi.fn().mockReturnValue({ connect: vi.fn(), disconnect: vi.fn() }),
getSessionBridgeKeys: vi.fn().mockReturnValue([]),
getMiddlewareChain: vi.fn().mockReturnValue(undefined),
getService: vi.fn().mockImplementation((name: string) => name === 'context' ? contextService : undefined),
};
return { deps, session, contextService, agentManager, newAgentInstance, resumedAgentInstance };
}
describe('AgentSwitchHandler — context injection on new agent', () => {
it('flushes recorder state BEFORE reading context for new agent', async () => {
const { deps, contextService } = makeDeps();
const handler = new AgentSwitchHandler(deps as any);
const callOrder: string[] = [];
contextService.flushSession.mockImplementation(async () => { callOrder.push('flush'); });
contextService.buildContext.mockImplementation(async () => { callOrder.push('buildContext'); return { markdown: '# History' }; });
await handler.switch('session-1', 'gemini');
expect(callOrder[0]).toBe('flush');
expect(callOrder[1]).toBe('buildContext');
});
it('passes noCache: true to buildContext to avoid stale context on repeated switches', async () => {
const { deps, contextService } = makeDeps();
const handler = new AgentSwitchHandler(deps as any);
await handler.switch('session-1', 'gemini');
expect(contextService.buildContext).toHaveBeenCalledWith(
expect.objectContaining({ type: 'session' }),
expect.objectContaining({ noCache: true }),
);
});
it('sets context on session after spawning new agent', async () => {
const { deps, session } = makeDeps();
const setContext = vi.spyOn(session, 'setContext');
const handler = new AgentSwitchHandler(deps as any);
await handler.switch('session-1', 'gemini');
expect(setContext).toHaveBeenCalledWith('# History\n\nTurn 1');
});
it('does not set context if buildContext returns null', async () => {
const { deps, session, contextService } = makeDeps();
contextService.buildContext.mockResolvedValue(null);
const setContext = vi.spyOn(session, 'setContext');
const handler = new AgentSwitchHandler(deps as any);
await handler.switch('session-1', 'gemini');
expect(setContext).not.toHaveBeenCalled();
});
});
describe('AgentSwitchHandler — resume logic without promptCount restriction', () => {
it('attempts to resume agent that previously had prompts (promptCount > 0)', async () => {
const session = makeSession();
// Simulate: agent 'gemini' was used before with 5 prompts
session.agentSwitchHistory = [{
agentName: 'gemini',
agentSessionId: 'old-gemini-session',
switchedAt: new Date().toISOString(),
promptCount: 5,
}];
const { deps, agentManager } = makeDeps(session);
const handler = new AgentSwitchHandler(deps as any);
await handler.switch('session-1', 'gemini');
expect(agentManager.resume).toHaveBeenCalledWith('gemini', '/workspace', 'old-gemini-session', []);
});
it('falls back to spawn with context when resume fails (e.g., session expired)', async () => {
const session = makeSession();
session.agentSwitchHistory = [{
agentName: 'gemini',
agentSessionId: 'expired-session',
switchedAt: new Date().toISOString(),
promptCount: 3,
}];
const { deps, agentManager, contextService } = makeDeps(session);
agentManager.resume.mockRejectedValue(new Error('Session expired'));
const handler = new AgentSwitchHandler(deps as any);
await handler.switch('session-1', 'gemini');
// Should fall back to spawn
expect(agentManager.spawn).toHaveBeenCalledWith('gemini', '/workspace', []);
// And inject context since it's a new agent
expect(contextService.buildContext).toHaveBeenCalled();
});
});

View File

@ -2,8 +2,6 @@ import { describe, it, expect, vi } from 'vitest';
import { Session } from '../sessions/session.js';
import { TypedEmitter } from '../utils/typed-emitter.js';
import type { AgentEvent } from '../types.js';
import { SessionBridge } from '../sessions/session-bridge.js';
import { SessionManager } from '../sessions/session-manager.js';
function mockAgentInstance(overrides?: { sessionId?: string }) {
const emitter = new TypedEmitter<{ agent_event: (event: AgentEvent) => void }>();
@ -26,69 +24,6 @@ function createTestSession(agentInstance?: any, agentName?: string) {
});
}
function mockAdapter() {
return {
sendMessage: vi.fn().mockResolvedValue(undefined),
renameSessionThread: vi.fn().mockResolvedValue(undefined),
sendPermissionRequest: vi.fn().mockResolvedValue(undefined),
sendSkillCommands: vi.fn().mockResolvedValue(undefined),
cleanupSkillCommands: vi.fn(),
cleanupSessionState: vi.fn().mockResolvedValue(undefined),
stripTTSBlock: vi.fn(),
flushPendingSkillCommands: vi.fn().mockResolvedValue(undefined),
} as any;
}
function mockBridgeDeps(overrides?: Partial<import('../sessions/session-bridge.js').BridgeDeps>) {
return {
messageTransformer: { transform: vi.fn().mockReturnValue({ type: 'text', text: '' }) } as any,
notificationManager: { notify: vi.fn().mockResolvedValue(undefined), notifyAll: vi.fn().mockResolvedValue(undefined) } as any,
sessionManager: { patchRecord: vi.fn().mockResolvedValue(undefined), getSessionRecord: vi.fn() } as any,
eventBus: { emit: vi.fn() } as any,
...overrides,
};
}
describe('SessionBridge config_option_update', () => {
it('awaits updateConfigOptions before persisting ACP state', async () => {
const agent = mockAgentInstance({ sessionId: 'sess-1' });
const session = createTestSession(agent, 'claude');
const adapter = mockAdapter();
const deps = mockBridgeDeps();
const bridge = new SessionBridge(session, adapter, deps);
bridge.connect();
// Track call order
const callOrder: string[] = [];
const originalUpdate = session.updateConfigOptions.bind(session);
session.updateConfigOptions = vi.fn(async (options) => {
callOrder.push('updateConfigOptions:start');
await originalUpdate(options);
callOrder.push('updateConfigOptions:end');
});
const originalPatch = deps.sessionManager.patchRecord;
deps.sessionManager.patchRecord = vi.fn(async (...args: any[]) => {
callOrder.push('patchRecord');
return originalPatch(...args);
});
// Emit config_option_update from agent
const configEvent = {
type: 'config_option_update' as const,
options: [{ id: 'mode', name: 'Mode', category: 'mode', type: 'select' as const, currentValue: 'code', options: [] }],
};
agent.emit('agent_event', configEvent);
// Wait for async processing
await vi.waitFor(() => {
expect(deps.sessionManager.patchRecord).toHaveBeenCalled();
});
// persistAcpState should happen AFTER updateConfigOptions completes
expect(callOrder.indexOf('updateConfigOptions:end')).toBeLessThan(callOrder.indexOf('patchRecord'));
});
});
describe('Agent Switch — Session-level integration', () => {
it('preserves session identity (same session.id) across switches', async () => {
const session = createTestSession(mockAgentInstance({ sessionId: 'old' }), 'claude');
@ -245,106 +180,4 @@ describe('Agent Switch — Session-level integration', () => {
expect(session.channelId).toBe(originalChannelId);
expect(session.workingDirectory).toBe(originalWorkDir);
});
it('buffers commands_update from new agent after switch', async () => {
const oldAgent = mockAgentInstance({ sessionId: 'old' });
const session = createTestSession(oldAgent, 'claude');
const newAgent = mockAgentInstance({ sessionId: 'new' });
await session.switchAgent('gemini', async () => newAgent);
// Emit commands_update from new agent BEFORE bridge connects
newAgent.emit('agent_event', {
type: 'commands_update',
commands: [{ name: '/test', description: 'test cmd' }],
});
expect(session.latestCommands).toEqual([{ name: '/test', description: 'test cmd' }]);
});
});
describe('SessionManager.shutdownAll()', () => {
it('snapshots full session state including acpState and promptCount', async () => {
const savedRecords: any[] = [];
const mockStore = {
save: vi.fn(async (record: any) => { savedRecords.push(structuredClone(record)); }),
get: vi.fn((id: string) => ({
sessionId: id,
agentSessionId: 'agent-1',
agentName: 'claude',
workingDir: '/workspace',
channelId: 'telegram',
status: 'active',
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
platform: {},
acpState: { configOptions: [{ id: 'model', currentValue: 'old-model' }] },
})),
flush: vi.fn(),
list: vi.fn(() => []),
findByPlatform: vi.fn(),
findByAgentSessionId: vi.fn(),
remove: vi.fn(),
} as any;
const manager = new SessionManager(mockStore);
const agent = mockAgentInstance({ sessionId: 'agent-1' });
const session = createTestSession(agent, 'claude');
session.name = 'test-session';
session.configOptions = [
{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'new-model', options: [] },
];
session.clientOverrides = { bypassPermissions: true };
await session.enqueuePrompt('test');
manager.registerSession(session);
await manager.shutdownAll();
const saved = savedRecords[0];
expect(saved.status).toBe('finished');
expect(saved.acpState.configOptions[0].currentValue).toBe('new-model');
expect(saved.clientOverrides).toEqual({ bypassPermissions: true });
expect(saved.currentPromptCount).toBe(1);
expect(mockStore.flush).toHaveBeenCalled();
});
});
describe('Lazy resume — acpState restore ordering', () => {
it('does not overwrite fresh agent configOptions with stale cache', () => {
const agent = mockAgentInstance({ sessionId: 'sess-1' });
(agent as any).initialSessionResponse = {
configOptions: [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'opus', options: [] }],
};
(agent as any).agentCapabilities = { supportsResume: true };
const session = createTestSession(agent, 'claude');
session.applySpawnResponse(agent.initialSessionResponse, agent.agentCapabilities);
expect(session.configOptions[0].currentValue).toBe('opus');
const cachedOptions = [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'sonnet', options: [] }];
if (session.configOptions.length === 0) {
session.setInitialConfigOptions(cachedOptions);
}
expect(session.configOptions[0].currentValue).toBe('opus');
});
it('uses cached configOptions when agent provides none', () => {
const agent = mockAgentInstance({ sessionId: 'sess-1' });
(agent as any).initialSessionResponse = {};
(agent as any).agentCapabilities = {};
const session = createTestSession(agent, 'claude');
session.applySpawnResponse(agent.initialSessionResponse, agent.agentCapabilities);
expect(session.configOptions).toEqual([]);
const cachedOptions = [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'sonnet', options: [] }];
if (session.configOptions.length === 0) {
session.setInitialConfigOptions(cachedOptions);
}
expect(session.configOptions[0].currentValue).toBe('sonnet');
});
});

View File

@ -1,129 +1,78 @@
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) {
function mockCore() {
const session = {
id: existingRecord?.sessionId ?? "assistant-1",
id: "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;
}),
createSession: vi.fn().mockResolvedValue(session),
connectSessionBridge: vi.fn(),
configManager: {
get: () => ({ defaultAgent: "claude-code" }),
resolveWorkspace: () => "/home/user/code",
},
sessionStore,
_session: session,
};
}
describe("AssistantManager", () => {
let core: ReturnType<typeof mockCore>;
let registry: AssistantRegistry;
let manager: AssistantManager;
beforeEach(() => {
core = mockCore();
registry = new AssistantRegistry();
manager = new AssistantManager(core as any, registry);
});
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("spawn creates session and stores it", async () => {
const session = await manager.spawn("telegram", "12345");
expect(core.createSession).toHaveBeenCalledWith(expect.objectContaining({
channelId: "telegram",
isAssistant: true,
initialName: "Assistant",
}));
expect(session.threadId).toBe("12345");
expect(manager.get("telegram")).toBe(session);
});
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");
await manager.spawn("telegram", "12345");
expect(manager.isAssistant("assistant-1")).toBe(true);
expect(manager.isAssistant("other-session")).toBe(false);
});
it("respawn destroys old and creates new", async () => {
await manager.spawn("telegram", "12345");
const oldSession = core._session;
const newSession = { ...oldSession, id: "assistant-2", threadId: "", enqueuePrompt: vi.fn().mockResolvedValue(undefined), destroy: vi.fn() };
core.createSession.mockResolvedValueOnce(newSession);
await manager.respawn("telegram", "12345");
expect(oldSession.destroy).toHaveBeenCalled();
expect(manager.get("telegram")).toBe(newSession);
});
it("concurrent respawn returns current session", async () => {
await manager.spawn("telegram", "12345");
core._session.destroy.mockImplementation(() => new Promise((r) => setTimeout(r, 100)));
const newSession = { ...core._session, id: "assistant-2", threadId: "", enqueuePrompt: vi.fn().mockResolvedValue(undefined), destroy: vi.fn() };
core.createSession.mockResolvedValueOnce(newSession);
const [r1, r2] = await Promise.all([
manager.respawn("telegram", "12345"),
manager.respawn("telegram", "12345"),
]);
expect(core._session.destroy).toHaveBeenCalledTimes(1);
});
});

View File

@ -105,6 +105,38 @@ describe('AgentCatalog cachePath isolation', () => {
})
})
describe('Config migration with custom configDir', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-test-'))
})
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true })
})
it('migrate-agents-to-store uses ctx.configDir when provided', async () => {
const { applyMigrations } = await import('../config/config-migrations.js')
const raw: Record<string, unknown> = {
agents: {
claude: { command: 'claude-agent-acp', args: [], env: {} },
},
defaultAgent: 'claude',
}
const { changed } = applyMigrations(raw, undefined, { configDir: tmpDir })
// Migration should have created agents.json in tmpDir (not ~/.openacp)
expect(changed).toBe(true)
const agentsPath = path.join(tmpDir, 'agents.json')
expect(fs.existsSync(agentsPath)).toBe(true)
const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'))
expect(data.installed.claude).toBeDefined()
})
})
describe('InstanceRegistry edge cases', () => {
let tmpDir: string
let registryPath: string

View File

@ -281,16 +281,6 @@ describe("DisplaySpecBuilder.buildToolSpec", () => {
});
describe("title generation for different tool kinds", () => {
it("read tool title supports camelCase filePath", () => {
const entry = makeEntry({
name: "read",
kind: "read",
rawInput: { filePath: "/foo/bar.ts", offset: 1, limit: 10 },
});
const spec = builder.buildToolSpec(entry, "medium");
expect(spec.title).toBe("/foo/bar.ts (lines 1–10)");
});
it("edit tool title from file_path", () => {
const entry = makeEntry({
name: "Edit",
@ -332,91 +322,5 @@ describe("DisplaySpecBuilder.buildToolSpec", () => {
expect(spec.title).toContain("foo");
expect(spec.title).toContain("*.ts");
});
it("apply_patch title extracts updated file path when kind is other", () => {
const entry = makeEntry({
name: "apply_patch",
kind: "other",
rawInput: {
patchText:
"*** Begin Patch\n*** Update File: /repo/src/app.ts\n@@\n-foo\n+bar\n*** End Patch",
},
});
const spec = builder.buildToolSpec(entry, "medium");
expect(spec.title).toBe("/repo/src/app.ts");
});
it("todowrite title summarizes progress when kind is other", () => {
const entry = makeEntry({
name: "todowrite",
kind: "other",
rawInput: {
todos: [
{ content: "A", status: "completed", priority: "high" },
{ content: "B", status: "in_progress", priority: "medium" },
{ content: "C", status: "pending", priority: "low" },
],
},
});
const spec = builder.buildToolSpec(entry, "medium");
expect(spec.title).toBe("Todo list (1/3 done, 1 active)");
});
it("keeps raw paths in title and exposes workingDirectory", () => {
const ctx = { id: "sess-1", workingDirectory: "/repo" };
const readSpec = builder.buildToolSpec(
makeEntry({
name: "read",
kind: "read",
rawInput: { filePath: "/repo/src/a.ts", offset: 10, limit: 5 },
}),
"medium",
ctx,
);
expect(readSpec.title).toBe("/repo/src/a.ts (lines 10–14)");
expect(readSpec.workingDirectory).toBe("/repo");
const writeSpec = builder.buildToolSpec(
makeEntry({
name: "write",
kind: "write",
rawInput: { filePath: "/repo/lib/output.json" },
}),
"medium",
ctx,
);
expect(writeSpec.title).toBe("/repo/lib/output.json");
const patchSpec = builder.buildToolSpec(
makeEntry({
name: "apply_patch",
kind: "other",
rawInput: {
patchText:
"*** Begin Patch\n*** Update File: /repo/packages/a/src/index.ts\n*** End Patch",
},
}),
"medium",
ctx,
);
expect(patchSpec.title).toBe("/repo/packages/a/src/index.ts");
});
it("apply_patch multi-file title shows first two raw paths", () => {
const spec = builder.buildToolSpec(
makeEntry({
name: "apply_patch",
kind: "other",
rawInput: {
patchText:
"*** Begin Patch\n*** Update File: /repo/a/one.ts\n*** Update File: /repo/b/two.ts\n*** Update File: /repo/c/three.ts\n*** End Patch",
},
}),
"medium",
{ id: "sess-1", workingDirectory: "/repo" },
);
expect(spec.title).toBe("/repo/a/one.ts, /repo/b/two.ts (+1 more)");
});
});
});

View File

@ -21,9 +21,6 @@ export interface ToolDisplaySpec {
viewerLinks?: ViewerLinks;
outputViewerLink?: string;
outputFallbackContent?: string;
/** Working directory of the session that produced this tool call.
* Adapters can use this to display relative paths instead of absolute ones. */
workingDirectory?: string;
status: string;
isNoise: boolean;
isHidden: boolean;
@ -55,47 +52,15 @@ function capitalize(s: string): string {
return s.length === 0 ? s : s[0].toUpperCase() + s.slice(1);
}
/**
* Try multiple field name variants (snake_case and camelCase) and return the
* first non-empty string value found. Needed because different agents use
* different naming conventions (e.g. Claude Code uses `file_path`, OpenCode
* uses `filePath`).
*/
function getStringField(input: Record<string, unknown>, keys: string[]): string | null {
for (const key of keys) {
const value = input[key];
if (typeof value === "string" && value.trim().length > 0) return value;
}
return null;
}
/**
* Extract target file paths from an apply_patch patch text.
* Handles "Update File", "Add File", and "Delete File" directives.
*/
function parseApplyPatchTargets(patchText: string): string[] {
const targets: string[] = [];
const seen = new Set<string>();
for (const line of patchText.split("\n")) {
const match = line.match(/^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s+(.+)$/);
if (!match) continue;
const p = match[1].trim();
if (p && !seen.has(p)) { seen.add(p); targets.push(p); }
}
return targets;
}
function buildTitle(entry: ToolEntry, kind: string): string {
// Explicit overrides take highest priority
if (entry.displayTitle) return entry.displayTitle;
if (entry.displaySummary) return entry.displaySummary;
const input = asRecord(entry.rawInput);
const nameLower = entry.name.toLowerCase();
if (kind === "read") {
// Support both snake_case (Claude Code) and camelCase (OpenCode) field names
const filePath = getStringField(input, ["file_path", "filePath", "path"]);
const filePath = typeof input.file_path === "string" ? input.file_path : null;
if (filePath) {
// start_line/end_line style
const startLine = typeof input.start_line === "number" ? input.start_line : null;
@ -113,8 +78,12 @@ function buildTitle(entry: ToolEntry, kind: string): string {
}
if (kind === "edit" || kind === "write" || kind === "delete") {
// Support both snake_case and camelCase field names
const filePath = getStringField(input, ["file_path", "filePath", "path"]);
const filePath =
typeof input.file_path === "string"
? input.file_path
: typeof input.path === "string"
? input.path
: null;
if (filePath) return filePath;
return capitalize(entry.name);
}
@ -155,39 +124,6 @@ function buildTitle(entry: ToolEntry, kind: string): string {
return capitalize(entry.name);
}
// Fallbacks for tools that often come through with kind="other"
if (nameLower === "apply_patch") {
const patchText = getStringField(input, ["patchText", "patch_text"]);
if (patchText) {
const targets = parseApplyPatchTargets(patchText);
if (targets.length === 1) return targets[0];
if (targets.length > 1) {
const shown = targets.slice(0, 2).join(", ");
const remaining = targets.length - 2;
return remaining > 0 ? `${shown} (+${remaining} more)` : shown;
}
}
return "apply_patch";
}
if (nameLower === "todowrite") {
const todos = Array.isArray(input.todos) ? input.todos : [];
if (todos.length > 0) {
const inProgress = todos.filter((t) => {
if (!t || typeof t !== "object") return false;
const status = (t as Record<string, unknown>).status;
return status === "in_progress";
}).length;
const completed = todos.filter((t) => {
if (!t || typeof t !== "object") return false;
const status = (t as Record<string, unknown>).status;
return status === "completed";
}).length;
return `Todo list (${completed}/${todos.length} done${inProgress > 0 ? `, ${inProgress} active` : ""})`;
}
return "Todo list";
}
if (kind === "fetch" || kind === "web") {
const url = typeof input.url === "string" ? input.url : null;
if (url && url !== "undefined") return url.length > 60 ? url.slice(0, 57) + "..." : url;
@ -197,46 +133,13 @@ function buildTitle(entry: ToolEntry, kind: string): string {
}
// Show skill name for Skill tool calls (e.g. Claude Code's Skill tool)
if (nameLower === "skill" && typeof input.skill === "string" && input.skill) {
if (entry.name.toLowerCase() === "skill" && typeof input.skill === "string" && input.skill) {
return input.skill;
}
// apply_patch: well-known tool used by multiple agents (OpenCode, Codex, etc.)
// Extract target file paths from the patch text for a meaningful title.
if (nameLower === "apply_patch") {
const patchText = getStringField(input, ["patchText", "patch_text"]);
if (patchText) {
const targets = parseApplyPatchTargets(patchText);
if (targets.length === 1) return targets[0];
if (targets.length > 1) {
const shown = targets.slice(0, 2).join(", ");
const rest = targets.length - 2;
return rest > 0 ? `${shown} (+${rest} more)` : shown;
}
}
return "apply_patch";
}
// todowrite / TodoWrite: well-known todo list tool (Claude Code, others)
// Summarise progress so the card shows "Todo list (2/5 done, 1 active)"
// rather than just the bare tool name.
if (nameLower === "todowrite") {
const todos = Array.isArray(input.todos) ? input.todos : [];
if (todos.length > 0) {
const completed = todos.filter((t) => isRecord(t) && t.status === "completed").length;
const active = todos.filter((t) => isRecord(t) && t.status === "in_progress").length;
return `Todo list (${completed}/${todos.length} done${active > 0 ? `, ${active} active` : ""})`;
}
return "Todo list";
}
return entry.name;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function buildOutputSummary(content: string): string {
const lines = content.split("\n").length;
return `${lines} line${lines === 1 ? "" : "s"} of output`;
@ -337,7 +240,6 @@ export class DisplaySpecBuilder {
viewerLinks: entry.viewerLinks,
outputViewerLink,
outputFallbackContent,
workingDirectory: sessionContext?.workingDirectory,
status: entry.status,
isNoise: entry.isNoise,
isHidden,

View File

@ -76,11 +76,6 @@ export class Draft {
} finally {
this.firstFlushPending = false
}
// Re-flush if buffer changed during the async operation
if (this.buffer !== snapshot) {
return this.flush()
}
}
}

View File

@ -10,7 +10,6 @@ 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";
import { Hook, BusEvent, SessionEv } from "./events.js";
const log = createChildLogger({ module: "agent-switch" });
@ -21,8 +20,7 @@ export interface AgentSwitchDeps {
eventBus: EventBus;
adapters: Map<string, IChannelAdapter>;
bridges: Map<string, SessionBridge>;
createBridge: (session: Session, adapter: IChannelAdapter, adapterId?: string) => SessionBridge;
getSessionBridgeKeys: (sessionId: string) => string[];
createBridge: (session: Session, adapter: IChannelAdapter) => SessionBridge;
getMiddlewareChain: () => MiddlewareChain | undefined;
getService: <T>(name: string) => T | undefined;
}
@ -57,7 +55,7 @@ export class AgentSwitchHandler {
// 1. Middleware: agent:beforeSwitch (blocking)
const middlewareChain = this.deps.getMiddlewareChain();
const result = await middlewareChain?.execute(Hook.AGENT_BEFORE_SWITCH, {
const result = await middlewareChain?.execute('agent:beforeSwitch', {
sessionId,
fromAgent,
toAgent,
@ -67,33 +65,26 @@ export class AgentSwitchHandler {
// 2. Determine resume vs new
const lastEntry = session.findLastSwitchEntry(toAgent);
const caps = getAgentCapabilities(toAgent);
const canResume = !!(lastEntry && caps.supportsResume);
let resumed = false;
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(SessionEv.AGENT_EVENT, startEvent);
eventBus.emit(BusEvent.AGENT_EVENT, { sessionId, event: startEvent });
eventBus.emit(BusEvent.SESSION_AGENT_SWITCH, {
session.emit("agent_event", startEvent);
eventBus.emit("agent:event", { sessionId, event: startEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
status: "starting",
});
// 3. Disconnect ALL bridges for this session
const sessionBridgeKeys = this.deps.getSessionBridgeKeys(sessionId);
const hadBridges = sessionBridgeKeys.length > 0;
for (const key of sessionBridgeKeys) {
const bridge = bridges.get(key);
if (bridge) {
bridges.delete(key);
bridge.disconnect();
}
}
// 3. Disconnect bridge
const bridge = bridges.get(sessionId);
if (bridge) bridge.disconnect();
const switchAdapter = adapters.get(session.channelId);
if (switchAdapter?.sendSkillCommands) {
@ -106,42 +97,30 @@ export class AgentSwitchHandler {
const fromAgentSessionId = session.agentSessionId;
// 4. Switch agent on session (with rollback on failure)
const fileService = this.deps.getService<import('../plugins/file-service/file-service.js').FileService>('file-service');
const configAllowedPaths = configManager.get().workspace?.security?.allowedPaths ?? [];
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);
try {
const instance = await agentManager.resume(toAgent, session.workingDirectory, lastEntry!.agentSessionId, configAllowedPaths);
if (fileService) instance.addAllowedPath(fileService.baseDir);
resumed = true;
return instance;
} catch {
// Resume failed (session expired or unavailable) — fall through to spawn with context
log.warn({ sessionId, toAgent }, "Resume failed, falling back to new agent with context injection");
}
}
const instance = await agentManager.spawn(toAgent, session.workingDirectory, configAllowedPaths);
if (fileService) instance.addAllowedPath(fileService.baseDir);
try {
const contextService = this.deps.getService<ContextManager>('context');
if (contextService) {
const config = configManager.get();
const labelAgent = config.agentSwitch?.labelHistory ?? true;
await contextService.flushSession(sessionId);
const contextResult = await contextService.buildContext(
{ type: 'session', value: sessionId, repoPath: session.workingDirectory },
{ labelAgent, noCache: true },
);
if (contextResult?.markdown) {
session.setContext(contextResult.markdown);
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
}
} catch {
// Context injection is best-effort
return instance;
}
return instance;
});
const successEvent: AgentEvent = {
@ -150,9 +129,9 @@ export class AgentSwitchHandler {
? `Switched to ${toAgent} (resumed previous session).`
: `Switched to ${toAgent} (new session).`,
};
session.emit(SessionEv.AGENT_EVENT, successEvent);
eventBus.emit(BusEvent.AGENT_EVENT, { sessionId, event: successEvent });
eventBus.emit(BusEvent.SESSION_AGENT_SWITCH, {
session.emit("agent_event", successEvent);
eventBus.emit("agent:event", { sessionId, event: successEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
@ -166,9 +145,9 @@ export class AgentSwitchHandler {
type: "system_message",
message: `Failed to switch to ${toAgent}: ${errorMessage}`,
};
session.emit(SessionEv.AGENT_EVENT, failedEvent);
eventBus.emit(BusEvent.AGENT_EVENT, { sessionId, event: failedEvent });
eventBus.emit(BusEvent.SESSION_AGENT_SWITCH, {
session.emit("agent_event", failedEvent);
eventBus.emit("agent:event", { sessionId, event: failedEvent });
eventBus.emit("session:agentSwitch", {
sessionId,
fromAgent,
toAgent,
@ -189,12 +168,9 @@ export class AgentSwitchHandler {
session.agentInstance = oldInstance;
session.agentName = fromAgent;
session.agentSessionId = oldInstance.sessionId;
// Reconnect all bridges on rollback
for (const adapterId of session.attachedAdapters) {
const adapter = adapters.get(adapterId);
if (adapter) {
createBridge(session, adapter, adapterId).connect();
}
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) {
@ -204,15 +180,11 @@ export class AgentSwitchHandler {
throw err;
}
// 5. Reconnect bridges for ALL attached adapters
if (hadBridges) {
for (const adapterId of session.attachedAdapters) {
const adapter = adapters.get(adapterId);
if (adapter) {
createBridge(session, adapter, adapterId).connect();
} else {
log.warn({ sessionId, adapterId }, "Adapter not available during switch reconnect, skipping bridge");
}
// 5. Reconnect bridge
if (bridge) {
const adapter = adapters.get(session.channelId);
if (adapter) {
createBridge(session, adapter).connect();
}
}
@ -226,7 +198,7 @@ export class AgentSwitchHandler {
});
// 7. Middleware: agent:afterSwitch (fire-and-forget)
middlewareChain?.execute(Hook.AGENT_AFTER_SWITCH, {
middlewareChain?.execute('agent:afterSwitch', {
sessionId,
fromAgent,
toAgent,

View File

@ -1,77 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { PathGuard } from "../../security/path-guard.js";
/**
* Tests that PathGuard correctly handles paths from workspace.security.allowedPaths config.
*
* AgentInstance.spawnSubprocess() now accepts extraAllowedPaths so the config-level
* whitelist is passed through to the PathGuard at spawn time — before any subsequent
* addAllowedPath() calls from SessionFactory.
*
* We test PathGuard directly since AgentInstance requires a real subprocess.
*/
describe("PathGuard with config-level allowedPaths", () => {
let tmpDir: string;
let workspaceDir: string;
let configAllowedDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-allowed-"));
workspaceDir = path.join(tmpDir, "workspace");
configAllowedDir = path.join(tmpDir, "shared-assets");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(configAllowedDir, { recursive: true });
fs.writeFileSync(path.join(workspaceDir, "app.ts"), "const x = 1;");
fs.writeFileSync(path.join(configAllowedDir, "logo.png"), "png-data");
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it("allows reading from workspace cwd", () => {
const guard = new PathGuard({
cwd: workspaceDir,
allowedPaths: [],
ignorePatterns: [],
});
const result = guard.validatePath(path.join(workspaceDir, "app.ts"), "read");
expect(result.allowed).toBe(true);
});
it("blocks reading from external dir without allowedPaths", () => {
const guard = new PathGuard({
cwd: workspaceDir,
allowedPaths: [],
ignorePatterns: [],
});
const result = guard.validatePath(path.join(configAllowedDir, "logo.png"), "read");
expect(result.allowed).toBe(false);
});
it("allows reading from external dir when listed in allowedPaths", () => {
const guard = new PathGuard({
cwd: workspaceDir,
allowedPaths: [configAllowedDir],
ignorePatterns: [],
});
const result = guard.validatePath(path.join(configAllowedDir, "logo.png"), "read");
expect(result.allowed).toBe(true);
});
it("addAllowedPath() after construction also grants access", () => {
const guard = new PathGuard({
cwd: workspaceDir,
allowedPaths: [],
ignorePatterns: [],
});
guard.addAllowedPath(configAllowedDir);
const result = guard.validatePath(path.join(configAllowedDir, "logo.png"), "read");
expect(result.allowed).toBe(true);
});
});
import { beforeEach, afterEach } from "vitest";

View File

@ -39,14 +39,6 @@ describe("agent-dependencies", () => {
const caps = getAgentCapabilities("unknown");
expect(caps.supportsResume).toBe(false);
});
it("returns opencode resume and plugin integration", () => {
const caps = getAgentCapabilities("opencode");
expect(caps.supportsResume).toBe(true);
expect(caps.resumeCommand?.("sess-123")).toBe("opencode --session sess-123");
expect(caps.integration?.strategy).toBe("plugin");
expect(caps.integration?.handoffCommandName).toBe("openacp:handoff");
});
});
describe("REGISTRY_AGENT_ALIASES", () => {

View File

@ -1,4 +1,4 @@
import { describe, it, expect, vi } from "vitest";
import { describe, it, expect } from "vitest";
import type { AgentEvent, ConfigOption } from "../../types.js";
/**
@ -137,83 +137,6 @@ describe("AgentInstance tool event rawOutput field", () => {
});
});
describe("AgentInstance setConfigOption legacy fallback", () => {
it("falls back to setSessionMode when setSessionConfigOption returns -32601 for mode", async () => {
const { AgentInstance } = await import("../agent-instance.js");
const instance = Object.create(AgentInstance.prototype) as InstanceType<typeof AgentInstance>;
const setSessionMode = vi.fn().mockResolvedValue({});
const setSessionConfigOption = vi.fn().mockRejectedValue(
Object.assign(new Error('"Method not found": session/set_config_option'), { code: -32601 })
);
(instance as any).sessionId = "sess-1";
(instance as any).connection = { setSessionConfigOption, setSessionMode, unstable_setSessionModel: vi.fn() };
const result = await instance.setConfigOption("mode", { type: "select", value: "architect" });
expect(setSessionMode).toHaveBeenCalledWith({ sessionId: "sess-1", modeId: "architect" });
expect(result).toEqual({ configOptions: [] });
});
it("falls back to unstable_setSessionModel when setSessionConfigOption returns -32601 for model", async () => {
const { AgentInstance } = await import("../agent-instance.js");
const instance = Object.create(AgentInstance.prototype) as InstanceType<typeof AgentInstance>;
const unstable_setSessionModel = vi.fn().mockResolvedValue({});
const setSessionConfigOption = vi.fn().mockRejectedValue(
Object.assign(new Error('"Method not found": session/set_config_option'), { code: -32601 })
);
(instance as any).sessionId = "sess-1";
(instance as any).connection = { setSessionConfigOption, setSessionMode: vi.fn(), unstable_setSessionModel };
const result = await instance.setConfigOption("model", { type: "select", value: "gemini-2.5-pro" });
expect(unstable_setSessionModel).toHaveBeenCalledWith({ sessionId: "sess-1", modelId: "gemini-2.5-pro" });
expect(result).toEqual({ configOptions: [] });
});
it("rethrows -32601 when configId is not mode or model", async () => {
const { AgentInstance } = await import("../agent-instance.js");
const instance = Object.create(AgentInstance.prototype) as InstanceType<typeof AgentInstance>;
const err = Object.assign(new Error('"Method not found": session/set_config_option'), { code: -32601 });
(instance as any).sessionId = "sess-1";
(instance as any).connection = { setSessionConfigOption: vi.fn().mockRejectedValue(err) };
await expect(
instance.setConfigOption("thought_level", { type: "select", value: "high" })
).rejects.toThrow(err);
});
it("rethrows non-32601 errors without fallback", async () => {
const { AgentInstance } = await import("../agent-instance.js");
const instance = Object.create(AgentInstance.prototype) as InstanceType<typeof AgentInstance>;
const err = Object.assign(new Error("Internal error"), { code: -32603 });
(instance as any).sessionId = "sess-1";
(instance as any).connection = { setSessionConfigOption: vi.fn().mockRejectedValue(err) };
await expect(
instance.setConfigOption("mode", { type: "select", value: "architect" })
).rejects.toThrow(err);
});
it("returns full configOptions when setSessionConfigOption succeeds", async () => {
const { AgentInstance } = await import("../agent-instance.js");
const instance = Object.create(AgentInstance.prototype) as InstanceType<typeof AgentInstance>;
const configOptions = [{ id: "mode", name: "Mode", type: "select" as const, currentValue: "architect", options: [] }];
(instance as any).sessionId = "sess-1";
(instance as any).connection = {
setSessionConfigOption: vi.fn().mockResolvedValue({ configOptions }),
};
const result = await instance.setConfigOption("mode", { type: "select", value: "architect" });
expect(result.configOptions).toEqual(configOptions);
});
});
describe("AgentInstance new ACP methods exist", () => {
// We import the class to verify method existence on the prototype
it("has setConfigOption method", async () => {

View File

@ -1,82 +0,0 @@
import { describe, it, expect } from "vitest";
import {
SUPPORTED_IMAGE_MIMES,
buildAttachmentNote,
} from "../attachment-blocks.js";
import type { Attachment } from "../../types.js";
function makeAtt(overrides: Partial<Attachment> = {}): Attachment {
return {
type: "image",
filePath: "/tmp/test.jpg",
fileName: "test.jpg",
mimeType: "image/jpeg",
size: 1024,
...overrides,
};
}
describe("SUPPORTED_IMAGE_MIMES", () => {
it("includes standard image formats", () => {
expect(SUPPORTED_IMAGE_MIMES.has("image/jpeg")).toBe(true);
expect(SUPPORTED_IMAGE_MIMES.has("image/png")).toBe(true);
expect(SUPPORTED_IMAGE_MIMES.has("image/gif")).toBe(true);
expect(SUPPORTED_IMAGE_MIMES.has("image/webp")).toBe(true);
});
it("includes modern image formats", () => {
expect(SUPPORTED_IMAGE_MIMES.has("image/avif")).toBe(true);
expect(SUPPORTED_IMAGE_MIMES.has("image/heic")).toBe(true);
expect(SUPPORTED_IMAGE_MIMES.has("image/heif")).toBe(true);
});
});
describe("buildAttachmentNote", () => {
const TEN_MB = 10 * 1024 * 1024;
it("returns null when attachment should be included normally (image, supported MIME, not too large)", () => {
const att = makeAtt({ size: 1024, mimeType: "image/jpeg" });
const note = buildAttachmentNote(att, { image: true, audio: false });
expect(note).toBeNull();
});
it("returns size-exceeded message when attachment is too large", () => {
const att = makeAtt({ size: TEN_MB + 1, fileName: "big-photo.jpg" });
const note = buildAttachmentNote(att, { image: true, audio: false });
expect(note).toMatch(/too large/);
expect(note).toMatch(/big-photo\.jpg/);
expect(note).toMatch(/10MB limit/);
});
it("returns unsupported-format message for unsupported image MIME", () => {
const att = makeAtt({ mimeType: "image/tiff" });
const note = buildAttachmentNote(att, { image: true, audio: false });
expect(note).toMatch(/not supported/);
expect(note).toMatch(/image\/tiff/);
});
it("returns null for avif image (now supported)", () => {
const att = makeAtt({ mimeType: "image/avif", size: 1024 });
const note = buildAttachmentNote(att, { image: true, audio: false });
expect(note).toBeNull();
});
it("returns null for heic image (now supported)", () => {
const att = makeAtt({ mimeType: "image/heic", size: 1024 });
const note = buildAttachmentNote(att, { image: true, audio: false });
expect(note).toBeNull();
});
it("returns null for audio when capabilities support it and not too large", () => {
const att = makeAtt({ type: "audio", mimeType: "audio/wav", size: 1024 });
const note = buildAttachmentNote(att, { image: false, audio: true });
expect(note).toBeNull();
});
it("returns size-exceeded message for large audio", () => {
const att = makeAtt({ type: "audio", mimeType: "audio/wav", fileName: "voice.wav", size: TEN_MB + 1 });
const note = buildAttachmentNote(att, { image: false, audio: true });
expect(note).toMatch(/too large/);
expect(note).toMatch(/voice\.wav/);
});
});

View File

@ -137,10 +137,6 @@ export class AgentCatalog {
const dist = resolveDistribution(agent);
const availability = checkDependencies(agent.id);
// An uninstalled agent is "available" (shows Install button) as long as a
// distribution exists for this platform. Missing external dependencies
// (e.g. claude CLI, codex CLI) are surfaced via missingDeps so the UI can
// show post-install setup instructions — they should NOT block installation.
items.push({
key: alias,
registryId: agent.id,
@ -149,7 +145,7 @@ export class AgentCatalog {
description: agent.description,
distribution: dist?.type ?? "binary",
installed: false,
available: dist !== null,
available: dist !== null && availability.available,
missingDeps: availability.missing?.map((m) => m.label),
});
}
@ -190,15 +186,6 @@ export class AgentCatalog {
return installAgent(agent, this.store, progress, this.agentsDir);
}
/**
* Register an agent directly into the catalog store without going through
* the registry installer. Used to pre-register bundled agents (e.g. Claude)
* when their CLI dependency is not yet installed.
*/
registerFallbackAgent(key: string, data: InstalledAgent): void {
this.store.addAgent(key, data);
}
async uninstall(key: string): Promise<{ ok: boolean; error?: string }> {
if (!this.store.hasAgent(key)) {
return { ok: false, error: `"${key}" is not installed.` };

View File

@ -14,8 +14,7 @@ export interface AgentSetupInfo {
loginCommand?: string;
}
export interface AgentHooksIntegrationSpec {
strategy: "hooks";
export interface AgentIntegrationSpec {
hookEvent: string;
settingsPath: string;
settingsFormat: "settings_json" | "hooks_json";
@ -29,18 +28,6 @@ export interface AgentHooksIntegrationSpec {
workingDirVar?: string;
}
export interface AgentPluginIntegrationSpec {
strategy: "plugin";
pluginProvider: "opencode";
commandsPath: string;
pluginsPath: string;
handoffCommandName: string;
handoffCommandFile: string;
pluginFileName: string;
}
export type AgentIntegrationSpec = AgentHooksIntegrationSpec | AgentPluginIntegrationSpec;
export interface AgentCapability {
supportsResume: boolean;
resumeCommand?: (sessionId: string) => string;
@ -201,7 +188,6 @@ const AGENT_CAPABILITIES: Record<string, AgentCapability> = {
supportsResume: true,
resumeCommand: (sid) => `claude --resume ${sid}`,
integration: {
strategy: "hooks",
hookEvent: "UserPromptSubmit",
settingsPath: "~/.claude/settings.json",
settingsFormat: "settings_json",
@ -219,7 +205,6 @@ const AGENT_CAPABILITIES: Record<string, AgentCapability> = {
supportsResume: true,
resumeCommand: (sid) => `cursor --resume ${sid}`,
integration: {
strategy: "hooks",
hookEvent: "beforeSubmitPrompt",
settingsPath: "~/.cursor/hooks.json",
settingsFormat: "hooks_json",
@ -235,7 +220,6 @@ const AGENT_CAPABILITIES: Record<string, AgentCapability> = {
supportsResume: true,
resumeCommand: (sid) => `gemini --resume ${sid}`,
integration: {
strategy: "hooks",
hookEvent: "BeforeAgent",
settingsPath: "~/.gemini/settings.json",
settingsFormat: "settings_json",
@ -248,7 +232,6 @@ const AGENT_CAPABILITIES: Record<string, AgentCapability> = {
supportsResume: true,
resumeCommand: () => `cline --continue`,
integration: {
strategy: "hooks",
hookEvent: "TaskStart",
settingsPath: "~/.cline/settings.json",
settingsFormat: "settings_json",
@ -269,19 +252,6 @@ const AGENT_CAPABILITIES: Record<string, AgentCapability> = {
supportsResume: true,
resumeCommand: (sid) => `amp threads continue ${sid}`,
},
opencode: {
supportsResume: true,
resumeCommand: (sid) => `opencode --session ${sid}`,
integration: {
strategy: "plugin",
pluginProvider: "opencode",
commandsPath: "~/.config/opencode/commands/",
pluginsPath: "~/.config/opencode/plugins/",
handoffCommandName: "openacp:handoff",
handoffCommandFile: "openacp-handoff.md",
pluginFileName: "openacp-handoff.js",
},
},
};
export const REGISTRY_AGENT_ALIASES: Record<string, string> = {

View File

@ -22,7 +22,7 @@ export function verifyChecksum(buffer: Buffer, expectedHash: string): void {
}
}
export function validateArchiveContents(entries: string[], destDir: string): void {
export function validateTarContents(entries: string[], destDir: string): void {
for (const entry of entries) {
// Check for path traversal segments, not just substring — avoids false positives
// on filenames like "setup..sh" or "..config" that are not traversal attacks.
@ -36,9 +36,6 @@ export function validateArchiveContents(entries: string[], destDir: string): voi
}
}
/** @deprecated Use validateArchiveContents instead */
export const validateTarContents = validateArchiveContents;
export function validateUninstallPath(binaryPath: string, agentsDir: string): void {
const realPath = path.resolve(binaryPath);
const realAgentsDir = path.resolve(agentsDir);
@ -164,7 +161,17 @@ export async function installAgent(
const agentKey = getAgentAlias(agent.id);
await progress?.onStart(agent.id, agent.name);
// 1. Resolve distribution
// 1. Check dependencies
await progress?.onStep("Checking requirements...");
const depResult = checkDependencies(agent.id);
if (!depResult.available) {
const hints = depResult.missing!.map((m) => ` ${m.label}: ${m.installHint}`).join("\n");
const msg = `${agent.name} needs some tools installed first:\n${hints}`;
await progress?.onError(msg);
return { ok: false, agentKey, error: msg };
}
// 2. Resolve distribution
const dist = resolveDistribution(agent);
if (!dist) {
const platformKey = getPlatformKey();
@ -173,18 +180,14 @@ export async function installAgent(
return { ok: false, agentKey, error: msg };
}
// 2. Check runtime availability (hard requirement — uvx/npx must exist to run)
// 3. Check runtime
if (dist.type === "uvx" && !checkRuntimeAvailable("uvx")) {
const msg = `${agent.name} requires Python's uvx tool.\nInstall it with: pip install uv`;
await progress?.onError(msg, "pip install uv");
return { ok: false, agentKey, error: msg, hint: "pip install uv" };
}
// 3. Check external CLI dependencies (non-blocking — install proceeds, setup steps
// guide the user to install required CLIs afterward)
const depResult = checkDependencies(agent.id);
// 4. Install based on distribution type
// 4. Install based on type
let binaryPath: string | undefined;
if (dist.type === "binary") {
@ -203,14 +206,9 @@ export async function installAgent(
const installed = buildInstalledAgent(agent.id, agent.name, agent.version, dist, binaryPath);
store.addAgent(agentKey, installed);
// 6. Build setup steps: prefer agent-specific steps; fall back to dep install hints
const setup = getAgentSetup(agent.id);
const setupSteps = setup?.setupSteps ?? (
depResult.missing?.map((m) => `${m.label}: ${m.installHint}`) ?? []
);
await progress?.onSuccess(agent.name);
return { ok: true, agentKey, setupSteps: setupSteps.length > 0 ? setupSteps : undefined };
return { ok: true, agentKey, setupSteps: setup?.setupSteps };
}
async function downloadAndExtract(
@ -306,7 +304,7 @@ async function extractTarGz(buffer: Buffer, destDir: string): Promise<void> {
// Validate contents BEFORE extraction
const listing = execFileSync("tar", ["tf", tmpFile], { stdio: "pipe" })
.toString().trim().split("\n").filter(Boolean);
validateArchiveContents(listing, destDir);
validateTarContents(listing, destDir);
// Safe to extract
execFileSync("tar", ["xzf", tmpFile, "-C", destDir], { stdio: "pipe" });
} finally {
@ -320,16 +318,6 @@ async function extractZip(buffer: Buffer, destDir: string): Promise<void> {
const tmpFile = path.join(destDir, "_archive.zip");
fs.writeFileSync(tmpFile, buffer);
try {
// Validate contents BEFORE extraction
const listing = execFileSync("unzip", ["-l", tmpFile], { stdio: "pipe" })
.toString().trim().split("\n").filter(Boolean);
// unzip -l output has header/footer lines; file paths are in the 4th column
const entries = listing
.slice(3, -2) // skip header (3 lines) and footer (2 lines)
.map((line) => line.trim().split(/\s+/).slice(3).join(" "))
.filter(Boolean);
validateArchiveContents(entries, destDir);
// Safe to extract
execFileSync("unzip", ["-o", tmpFile, "-d", destDir], { stdio: "pipe" });
} finally {
fs.unlinkSync(tmpFile);

View File

@ -24,7 +24,6 @@ import type {
SetConfigOptionValue,
} from "../types.js";
import { readTextFileWithRange } from "../utils/read-text-file.js";
import { SUPPORTED_IMAGE_MIMES, buildAttachmentNote } from "./attachment-blocks.js";
import type { MiddlewareChain } from "../plugin/middleware-chain.js";
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
import { TerminalManager } from "../sessions/terminal-manager.js";
@ -37,7 +36,6 @@ import type {
} from "@agentclientprotocol/sdk";
import { createDebugTracer, type DebugTracer } from "../utils/debug-tracer.js";
import { createChildLogger } from "../utils/log.js";
import { Hook, SessionEv } from "../events.js";
const log = createChildLogger({ module: "agent-instance" });
/** Find the nearest ancestor directory containing package.json */
@ -169,11 +167,6 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
middlewareChain?: MiddlewareChain;
debugTracer: DebugTracer | null = null;
/** Allow external callers (e.g. SessionFactory) to whitelist additional read paths */
addAllowedPath(p: string): void {
this.pathGuard.addAllowedPath(p);
}
// Callback — set by core when wiring events
onPermissionRequest: (request: PermissionRequest) => Promise<string> =
async () => "";
@ -186,7 +179,6 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
private static async spawnSubprocess(
agentDef: AgentDefinition,
workingDirectory: string,
allowedPaths: string[] = [],
): Promise<AgentInstance> {
const instance = new AgentInstance(agentDef.name);
const resolved = resolveAgentCommand(agentDef.command);
@ -202,7 +194,10 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
const ignorePatterns = PathGuard.loadIgnoreFile(workingDirectory);
instance.pathGuard = new PathGuard({
cwd: workingDirectory,
allowedPaths,
// allowedPaths is wired from workspace.security.allowedPaths config;
// spawnSubprocess would need to receive a SecurityConfig param to use it.
// Tracked as follow-up: pass workspace security config through spawn/resume call chain.
allowedPaths: [],
ignorePatterns,
});
@ -309,11 +304,9 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
{ sessionId: this.sessionId, exitCode: code, signal },
"Agent process exited",
);
// SIGINT/SIGTERM are graceful shutdown signals — not crashes
if (signal === "SIGINT" || signal === "SIGTERM") return;
if ((code !== 0 && code !== null) || signal) {
const stderr = this.stderrCapture.getLastLines();
this.emit(SessionEv.AGENT_EVENT, {
this.emit('agent_event', {
type: "error",
message: signal
? `Agent killed by signal ${signal}\n${stderr}`
@ -331,7 +324,6 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
agentDef: AgentDefinition,
workingDirectory: string,
mcpServers?: McpServerConfig[],
allowedPaths?: string[],
): Promise<AgentInstance> {
log.debug(
{ agentName: agentDef.name, command: agentDef.command },
@ -342,7 +334,6 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
const instance = await AgentInstance.spawnSubprocess(
agentDef,
workingDirectory,
allowedPaths,
);
const resolvedMcp = AgentInstance.mcpManager.resolve(mcpServers);
@ -350,20 +341,13 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
cwd: workingDirectory,
mcpServers: resolvedMcp as any,
});
log.info(response, 'newSession response');
instance.sessionId = response.sessionId;
instance.initialSessionResponse = response;
instance.debugTracer = createDebugTracer(response.sessionId, workingDirectory);
instance.setupCrashDetection();
log.info(
{
sessionId: response.sessionId,
durationMs: Date.now() - spawnStart,
configOptions: (response as any).configOptions ?? [],
agentCapabilities: instance.agentCapabilities ?? null,
},
{ sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
"Agent spawn complete",
);
return instance;
@ -374,7 +358,6 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
workingDirectory: string,
agentSessionId: string,
mcpServers?: McpServerConfig[],
allowedPaths?: string[],
): Promise<AgentInstance> {
log.debug({ agentName: agentDef.name, agentSessionId }, "Resuming agent");
const spawnStart = Date.now();
@ -382,52 +365,26 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
const instance = await AgentInstance.spawnSubprocess(
agentDef,
workingDirectory,
allowedPaths,
);
const resolvedMcp = AgentInstance.mcpManager.resolve(mcpServers);
try {
if (instance.agentCapabilities?.loadSession) {
// Agent supports session/load — preferred over unstable session/resume
const response = await instance.connection.loadSession({
sessionId: agentSessionId,
cwd: workingDirectory,
mcpServers: resolvedMcp as any,
});
instance.sessionId = agentSessionId;
instance.initialSessionResponse = response;
instance.debugTracer = createDebugTracer(agentSessionId, workingDirectory);
log.info(
{
sessionId: agentSessionId,
durationMs: Date.now() - spawnStart,
agentCapabilities: instance.agentCapabilities ?? null,
},
"Agent load complete",
);
} else {
const response = await instance.connection.unstable_resumeSession({
sessionId: agentSessionId,
cwd: workingDirectory,
});
instance.sessionId = response.sessionId;
instance.initialSessionResponse = response;
instance.debugTracer = createDebugTracer(response.sessionId, workingDirectory);
log.info(
{
sessionId: response.sessionId,
durationMs: Date.now() - spawnStart,
agentCapabilities: instance.agentCapabilities ?? null,
},
"Agent resume complete",
);
}
const response = await instance.connection.unstable_resumeSession({
sessionId: agentSessionId,
cwd: workingDirectory,
});
instance.sessionId = response.sessionId;
instance.initialSessionResponse = response;
instance.debugTracer = createDebugTracer(response.sessionId, workingDirectory);
log.info(
{ sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
"Agent resume complete",
);
} catch (err) {
log.warn(
{ err, agentSessionId },
"Resume failed, falling back to new session",
);
const resolvedMcp = AgentInstance.mcpManager.resolve(mcpServers);
const response = await instance.connection.newSession({
cwd: workingDirectory,
mcpServers: resolvedMcp as any,
@ -597,7 +554,7 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
}
if (event !== null) {
self.emit(SessionEv.AGENT_EVENT, event);
self.emit('agent_event', event);
}
},
@ -630,7 +587,7 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
}
// Hook: fs:beforeRead — modifiable, can block
if (self.middlewareChain) {
const result = await self.middlewareChain.execute(Hook.FS_BEFORE_READ, { sessionId: self.sessionId, path: p.path, line: p.line, limit: p.limit }, async (r) => r);
const result = await self.middlewareChain.execute('fs:beforeRead', { sessionId: self.sessionId, path: p.path, line: p.line, limit: p.limit }, async (r) => r);
if (!result) return { content: "" }; // blocked by middleware
p.path = result.path;
}
@ -651,7 +608,7 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
}
// Hook: fs:beforeWrite — modifiable, can block
if (self.middlewareChain) {
const result = await self.middlewareChain.execute(Hook.FS_BEFORE_WRITE, { sessionId: self.sessionId, path: writePath, content: writeContent }, async (r) => r);
const result = await self.middlewareChain.execute('fs:beforeWrite', { sessionId: self.sessionId, path: writePath, content: writeContent }, async (r) => r);
if (!result) return {}; // blocked by middleware
writePath = result.path;
writeContent = result.content;
@ -701,34 +658,11 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
configId: string,
value: SetConfigOptionValue,
): Promise<SetSessionConfigOptionResponse> {
try {
return await this.connection.setSessionConfigOption({
sessionId: this.sessionId,
configId,
...value,
} as any);
} catch (err) {
// Fall back to legacy setSessionMode / unstable_setSessionModel for agents
// (e.g. Gemini CLI) that implement the old separate methods instead of the
// unified session/set_config_option method (ACP -32601 Method Not Found).
if (typeof err === 'object' && err !== null && (err as any).code === -32601) {
if (configId === 'mode' && value.type === 'select') {
await this.connection.setSessionMode({
sessionId: this.sessionId,
modeId: value.value as string,
});
return { configOptions: [] };
}
if (configId === 'model' && value.type === 'select') {
await this.connection.unstable_setSessionModel({
sessionId: this.sessionId,
modelId: value.value as string,
});
return { configOptions: [] };
}
}
throw err;
}
return await this.connection.setSessionConfigOption({
sessionId: this.sessionId,
configId,
...value,
} as any);
}
async listSessions(
@ -779,17 +713,14 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
async prompt(text: string, attachments?: Attachment[]): Promise<PromptResponse> {
const contentBlocks: Array<Record<string, unknown>> = [{ type: "text", text }];
const capabilities = this.promptCapabilities ?? {};
// MIME types supported by Claude API for base64 image content
const SUPPORTED_IMAGE_MIMES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
for (const att of attachments ?? []) {
// Check if this attachment should be skipped (too large, unsupported format)
const skipNote = buildAttachmentNote(att, capabilities);
if (skipNote !== null) {
(contentBlocks[0] as { text: string }).text += `\n\n${skipNote}`;
continue;
}
const tooLarge = att.size > 10 * 1024 * 1024; // 10MB base64 guard
if (att.type === "image" && capabilities.image && SUPPORTED_IMAGE_MIMES.has(att.mimeType)) {
if (att.type === "image" && this.promptCapabilities?.image && !tooLarge && SUPPORTED_IMAGE_MIMES.has(att.mimeType)) {
const attCheck = this.pathGuard.validatePath(att.filePath, "read");
if (!attCheck.allowed) {
(contentBlocks[0] as { text: string }).text += `\n\n[Attachment access denied: ${attCheck.reason}]`;
@ -797,7 +728,7 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
}
const data = await fs.promises.readFile(att.filePath);
contentBlocks.push({ type: "image", data: data.toString("base64"), mimeType: att.mimeType });
} else if (att.type === "audio" && capabilities.audio) {
} else if (att.type === "audio" && this.promptCapabilities?.audio && !tooLarge) {
const attCheck = this.pathGuard.validatePath(att.filePath, "read");
if (!attCheck.allowed) {
(contentBlocks[0] as { text: string }).text += `\n\n[Attachment access denied: ${attCheck.reason}]`;
@ -807,9 +738,9 @@ export class AgentInstance extends TypedEmitter<AgentInstanceEvents> {
contentBlocks.push({ type: "audio", data: data.toString("base64"), mimeType: att.mimeType });
} else {
// Fallback: append file path to text so agent can read from disk
if (att.type === "image" || att.type === "audio") {
if ((att.type === "image" || att.type === "audio") && !tooLarge) {
log.debug(
{ type: att.type, capabilities },
{ type: att.type, capabilities: this.promptCapabilities ?? {} },
"Agent does not support %s content, falling back to file path",
att.type,
);

View File

@ -22,21 +22,19 @@ export class AgentManager {
async spawn(
agentName: string,
workingDirectory: string,
allowedPaths?: string[],
): Promise<AgentInstance> {
const agentDef = this.getAgent(agentName);
if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
return AgentInstance.spawn(agentDef, workingDirectory, undefined, allowedPaths);
return AgentInstance.spawn(agentDef, workingDirectory);
}
async resume(
agentName: string,
workingDirectory: string,
agentSessionId: string,
allowedPaths?: string[],
): Promise<AgentInstance> {
const agentDef = this.getAgent(agentName);
if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
return AgentInstance.resume(agentDef, workingDirectory, agentSessionId, undefined, allowedPaths);
return AgentInstance.resume(agentDef, workingDirectory, agentSessionId);
}
}

View File

@ -1,71 +0,0 @@
/**
* Attachment handling utilities for building ACP prompt content blocks.
*
* Extracted as a pure module so the logic can be unit-tested independently
* of AgentInstance (which requires a subprocess to instantiate).
*/
import type { Attachment } from "../types.js";
/** Image MIME types supported by the Claude API for base64 inline content. */
export const SUPPORTED_IMAGE_MIMES = new Set([
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/avif",
"image/heic",
"image/heif",
]);
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024; // 10 MB
export interface PromptCapabilities {
image?: boolean;
audio?: boolean;
}
/**
* Determines if an attachment should be skipped (not included as base64 content block).
*
* Returns a human-readable note to append to the prompt text when the attachment
* cannot be embedded, or null when the attachment should be included normally.
*
* This function does NOT read the file — it only classifies the attachment based
* on its metadata. Path validation and file reading remain in AgentInstance.prompt().
*/
export function buildAttachmentNote(
att: Attachment,
capabilities: PromptCapabilities,
): string | null {
const tooLarge = att.size > MAX_ATTACHMENT_SIZE;
if (tooLarge) {
const sizeMB = Math.round(att.size / 1024 / 1024);
return `[Attachment skipped: "${att.fileName}" is too large (${sizeMB}MB > 10MB limit)]`;
}
if (att.type === "image") {
if (!capabilities.image) {
// Agent doesn't support image content — will fall back to file path
return null;
}
if (!SUPPORTED_IMAGE_MIMES.has(att.mimeType)) {
return `[Attachment skipped: image format not supported (${att.mimeType})]`;
}
// Supported — include as base64 block
return null;
}
if (att.type === "audio") {
if (!capabilities.audio) {
// Agent doesn't support audio content — will fall back to file path
return null;
}
// Supported — include as base64 block
return null;
}
// Generic file attachment — always falls back to file path, no note needed
return null;
}

View File

@ -1,6 +1,5 @@
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' })
@ -12,19 +11,17 @@ interface AssistantManagerCore {
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 respawning = new Set<string>()
private pendingSystemPrompts = new Map<string, string>()
constructor(
@ -32,25 +29,22 @@ export class AssistantManager {
private registry: AssistantRegistry,
) {}
async getOrSpawn(channelId: string, threadId: string): Promise<Session> {
const existing = this.core.sessionStore?.findAssistant(channelId)
async spawn(channelId: string, threadId: string): Promise<Session> {
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,
})
session.threadId = threadId
this.sessions.set(channelId, session)
// Store system prompt for lazy initialization — it will be prepended
// to the first real user message so no unsolicited AI response is sent on startup.
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)',
)
log.info({ sessionId: session.id, channelId }, 'Assistant spawned (system prompt deferred)')
return session
}
@ -75,4 +69,19 @@ export class AssistantManager {
}
return false
}
async respawn(channelId: string, threadId: string): Promise<Session> {
if (this.respawning.has(channelId)) {
return this.sessions.get(channelId)!
}
this.respawning.add(channelId)
try {
const old = this.sessions.get(channelId)
if (old) await old.destroy()
return await this.spawn(channelId, threadId)
} finally {
this.respawning.delete(channelId)
}
}
}

View File

@ -5,4 +5,3 @@ export { createSessionsSection } from './sections/sessions.js'
export { createAgentsSection } from './sections/agents.js'
export { createConfigSection } from './sections/config.js'
export { createSystemSection } from './sections/system.js'
export { createRemoteSection } from './sections/remote.js'

View File

@ -1,55 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { createConfigSection } from "../config.js";
function makeCore(opts: {
workspaceBaseDir?: string
legacySpeechProvider?: string | null
speechService?: { isSTTAvailable(): boolean } | null
}) {
return {
configManager: {
get: vi.fn().mockReturnValue({
workspace: { baseDir: opts.workspaceBaseDir ?? "~/" },
speech: opts.legacySpeechProvider
? { stt: { provider: opts.legacySpeechProvider } }
: undefined,
}),
},
lifecycleManager: opts.speechService !== undefined
? { serviceRegistry: { get: vi.fn().mockReturnValue(opts.speechService) } }
: undefined,
} as any;
}
describe("createConfigSection", () => {
it("shows STT not configured when no speech service and no legacy config", () => {
const section = createConfigSection(makeCore({ speechService: null }));
const ctx = section.buildContext!();
expect(ctx).toContain("STT: Not configured");
});
it("shows STT configured when speech service isSTTAvailable returns true", () => {
const section = createConfigSection(makeCore({
speechService: { isSTTAvailable: () => true },
}));
const ctx = section.buildContext!();
expect(ctx).toContain("configured ✅");
});
it("shows STT not configured when speech service exists but isSTTAvailable returns false", () => {
const section = createConfigSection(makeCore({
speechService: { isSTTAvailable: () => false },
}));
const ctx = section.buildContext!();
expect(ctx).toContain("Not configured");
expect(ctx).not.toContain("✅");
});
it("shows STT not configured when no lifecycleManager", () => {
const section = createConfigSection(makeCore({
speechService: undefined, // no lifecycleManager
}));
const ctx = section.buildContext!();
expect(ctx).toContain("Not configured");
});
});

View File

@ -1,8 +1,7 @@
import type { AssistantSection } from '../assistant-registry.js'
export function createConfigSection(core: {
configManager: { get(): { workspace: { baseDir: string } } }
lifecycleManager?: { serviceRegistry: { get<T>(name: string): T | undefined } }
configManager: { get(): { workspace: { baseDir: string }; speech?: { stt?: { provider?: string } } } }
}): AssistantSection {
return {
id: 'core:config',
@ -10,11 +9,9 @@ export function createConfigSection(core: {
priority: 30,
buildContext: () => {
const config = core.configManager.get()
const speechSvc = core.lifecycleManager?.serviceRegistry.get<{ isSTTAvailable(): boolean }>('speech')
const sttActive = speechSvc ? speechSvc.isSTTAvailable() : false
return (
`Workspace base: ${config.workspace.baseDir}\n` +
`STT: ${sttActive ? 'configured ✅' : 'Not configured'}`
`STT: ${config.speech?.stt?.provider ? `${config.speech.stt.provider} ✅` : 'Not configured'}`
)
},
commands: [

View File

@ -1,27 +0,0 @@
import type { AssistantSection } from '../assistant-registry.js'
export function createRemoteSection(): AssistantSection {
return {
id: 'core:remote',
title: 'Remote Access',
priority: 35,
buildContext: () => {
return (
`Generate a one-time remote access link so the user can connect to this OpenACP instance from the app or a browser.\n\n` +
`The link contains a short-lived code (expires in 30 minutes, single-use) that exchanges for a long-lived token.\n\n` +
`Roles:\n` +
` admin — full control (default)\n` +
` viewer — read-only access\n\n` +
`The command automatically includes the tunnel URL if a tunnel is active. ` +
`Without a tunnel, the local link only works on the same machine.\n\n` +
`Always show both the link and QR code when available so the user can choose how to open it.`
)
},
commands: [
{ command: 'openacp remote', description: 'Generate remote access link (admin role, 24h expiry)' },
{ command: 'openacp remote --role viewer', description: 'Generate read-only access link' },
{ command: 'openacp remote --expire 48h', description: 'Generate link with custom expiry' },
{ command: 'openacp remote --no-qr', description: 'Skip QR code output' },
],
}
}

View File

@ -83,10 +83,8 @@ export class CommandRegistry {
if (cmd.scope) {
// If we deleted by short name, also delete qualified name
this.commands.delete(`${cmd.scope}:${cmd.name}`)
// If we deleted by qualified name, only delete short name if it points to the same command
if (this.commands.get(cmd.name) === cmd) {
this.commands.delete(cmd.name)
}
// If we deleted by qualified name, also delete short name
this.commands.delete(cmd.name)
}
}

View File

@ -53,7 +53,7 @@ const booleanOption: ConfigOption = {
// ── Helpers ──────────────────────────────────────────────────────────
function mockSession(configOptions: ConfigOption[] = [], overrides?: Partial<any>) {
const session: any = {
return {
id: 'test-session',
configOptions,
clientOverrides: {} as { bypassPermissions?: boolean },
@ -72,18 +72,6 @@ function mockSession(configOptions: ConfigOption[] = [], overrides?: Partial<any
middlewareChain: undefined as any,
...overrides,
}
// session.setConfigOption delegates to agentInstance and updates configOptions
session.setConfigOption = vi.fn(async (configId: string, value: any) => {
const response = await session.agentInstance.setConfigOption(configId, value)
if (response.configOptions && response.configOptions.length > 0) {
session.configOptions = response.configOptions
} else if (value.type === 'select') {
session.configOptions = session.configOptions.map((o: ConfigOption) =>
o.id === configId && o.type === 'select' ? { ...o, currentValue: value.value } : o
)
}
})
return session
}
function mockCore(session?: ReturnType<typeof mockSession>) {
@ -192,7 +180,7 @@ describe('Config Commands', () => {
it('sets mode when valid value provided', async () => {
const res = await registry.execute('/mode architect', baseArgs('test-session'))
expect(res.type).toBe('text')
expect(session.setConfigOption).toHaveBeenCalledWith(
expect(session.agentInstance.setConfigOption).toHaveBeenCalledWith(
'mode',
{ type: 'select', value: 'architect' },
)
@ -216,7 +204,7 @@ describe('Config Commands', () => {
expect(res.text).toContain('Code')
}
// Agent should NOT be called when already at target value
expect(session.setConfigOption).not.toHaveBeenCalled()
expect(session.agentInstance.setConfigOption).not.toHaveBeenCalled()
})
it('returns error for invalid value with "Unknown option" message', async () => {
@ -242,11 +230,7 @@ describe('Config Commands', () => {
})
await registry.execute('/mode architect', baseArgs('test-session'))
// setConfigOption on session updates configOptions from agent response
expect(session.setConfigOption).toHaveBeenCalledWith(
'mode',
{ type: 'select', value: 'architect' },
)
// configOptions set directly (skips middleware — already fired before agent call)
expect(session.configOptions).toEqual(updatedOptions)
})
@ -340,7 +324,7 @@ describe('Config Commands', () => {
it('sets model correctly with valid value', async () => {
const res = await registry.execute('/model opus', baseArgs('test-session'))
expect(res.type).toBe('text')
expect(session.setConfigOption).toHaveBeenCalledWith(
expect(session.agentInstance.setConfigOption).toHaveBeenCalledWith(
'model',
{ type: 'select', value: 'opus' },
)
@ -357,7 +341,7 @@ describe('Config Commands', () => {
if (res.type === 'text') {
expect(res.text).toContain('Already using')
}
expect(session.setConfigOption).not.toHaveBeenCalled()
expect(session.agentInstance.setConfigOption).not.toHaveBeenCalled()
})
})
@ -397,7 +381,7 @@ describe('Config Commands', () => {
it('sets thought level correctly', async () => {
const res = await registry.execute('/thought extended', baseArgs('test-session'))
expect(res.type).toBe('text')
expect(session.setConfigOption).toHaveBeenCalledWith(
expect(session.agentInstance.setConfigOption).toHaveBeenCalledWith(
'thinking',
{ type: 'select', value: 'extended' },
)
@ -420,7 +404,7 @@ describe('Config Commands', () => {
it('/bypass_permissions on switches to bypass mode', async () => {
const res = await registry.execute('/bypass_permissions on', baseArgs('test-session'))
expect(res.type).toBe('text')
expect(session.setConfigOption).toHaveBeenCalledWith(
expect(session.agentInstance.setConfigOption).toHaveBeenCalledWith(
'mode',
{ type: 'select', value: 'bypassPermissions' },
)
@ -435,7 +419,7 @@ describe('Config Commands', () => {
const res = await registry.execute('/bypass_permissions off', baseArgs('test-session'))
expect(res.type).toBe('text')
// Should set to first non-bypass option
expect(session.setConfigOption).toHaveBeenCalledWith(
expect(session.agentInstance.setConfigOption).toHaveBeenCalledWith(
'mode',
{ type: 'select', value: 'code' },
)
@ -475,7 +459,7 @@ describe('Config Commands', () => {
if (res.type === 'text') {
expect(res.text).toContain('already')
}
expect(session.setConfigOption).not.toHaveBeenCalled()
expect(session.agentInstance.setConfigOption).not.toHaveBeenCalled()
})
it('/bypass_permissions off when already off returns "already disabled" text', async () => {
@ -485,7 +469,7 @@ describe('Config Commands', () => {
if (res.type === 'text') {
expect(res.text).toContain('already')
}
expect(session.setConfigOption).not.toHaveBeenCalled()
expect(session.agentInstance.setConfigOption).not.toHaveBeenCalled()
})
})
@ -603,17 +587,10 @@ describe('Config Commands', () => {
expect(isPermissionBypass('auto_accept')).toBe(true)
})
it('detects "yolo" keyword', async () => {
const { isPermissionBypass } = await loadModule()
expect(isPermissionBypass('yolo')).toBe(true)
expect(isPermissionBypass('yolo_mode')).toBe(true)
})
it('is case-insensitive', async () => {
const { isPermissionBypass } = await loadModule()
expect(isPermissionBypass('BypassPermissions')).toBe(true)
expect(isPermissionBypass('DANGEROUS')).toBe(true)
expect(isPermissionBypass('YOLO')).toBe(true)
})
it('returns false for non-bypass values', async () => {
@ -666,7 +643,7 @@ describe('Config Commands', () => {
it('setConfigOption failure returns error', async () => {
session = mockSession([modeOption])
session.setConfigOption.mockRejectedValue(new Error('Agent rejected'))
session.agentInstance.setConfigOption.mockRejectedValue(new Error('Agent rejected'))
core = mockCore(session)
registry = new CommandRegistry()
const { registerConfigCommands } = await loadModule()
@ -713,7 +690,7 @@ describe('Config Commands', () => {
}
})
it('setConfigOption returns no configOptions, falls back to optimistic update', async () => {
it('setConfigOption returns no configOptions, skips update', async () => {
session = mockSession([modeOption])
session.agentInstance.setConfigOption.mockResolvedValue({})
core = mockCore(session)
@ -723,11 +700,7 @@ describe('Config Commands', () => {
const res = await registry.execute('/mode architect', baseArgs('test-session'))
expect(res.type).toBe('text')
// session.setConfigOption is still called — optimistic update path handles empty response
expect(session.setConfigOption).toHaveBeenCalledWith(
'mode',
{ type: 'select', value: 'architect' },
)
expect(session.updateConfigOptions).not.toHaveBeenCalled()
})
})
})

View File

@ -1,11 +1,7 @@
import type { CommandRegistry } from '../command-registry.js'
import type { CommandResponse } from '../plugin/types.js'
import type { OpenACPCore } from '../core.js'
import type { ConfigSelectChoice, ConfigSelectGroup } from '../types.js'
import { createChildLogger } from '../utils/log.js'
import { BusEvent } from '../events.js'
const log = createChildLogger({ module: 'commands/config' })
import type { ConfigOption, ConfigSelectChoice, ConfigSelectGroup } from '../types.js'
// ── Bypass keyword detection ─────────────────────────────────────────
@ -124,16 +120,29 @@ function registerCategoryCommand(
return { type: 'text', text: `Already using **${match.name}**.` } satisfies CommandResponse
}
// Fire middleware hook BEFORE sending to agent
if (session.middlewareChain) {
const result = await session.middlewareChain.execute('config:beforeChange', {
sessionId: session.id, configId: configOption.id,
oldValue: configOption.currentValue, newValue: raw,
}, async (p) => p)
if (!result) return { type: 'error', message: `This change was blocked by a plugin.` } satisfies CommandResponse
}
// Set value via agent
try {
await session.setConfigOption(configOption.id, { type: 'select', value: raw })
core.eventBus.emit(BusEvent.SESSION_CONFIG_CHANGED, { sessionId: session.id })
const response = await session.agentInstance.setConfigOption(
configOption.id,
{ type: 'select', value: raw },
)
if (response.configOptions) {
// Skip middleware hook on update — already validated above
session.configOptions = response.configOptions as ConfigOption[]
}
core.eventBus.emit('session:configChanged', { sessionId: session.id })
return { type: 'text', text: labels.successMsg(match.name, configOption.name) } satisfies CommandResponse
} catch (err) {
log.error({ err, commandName, configId: configOption.id }, 'setConfigOption failed')
const msg = err instanceof Error ? err.message
: typeof err === 'object' && err !== null && typeof (err as any).message === 'string'
? (err as any).message
: String(err)
const msg = err instanceof Error ? err.message : String(err)
return { type: 'error', message: `Could not change ${commandName}: ${msg}` } satisfies CommandResponse
}
},
@ -210,8 +219,14 @@ function registerDangerousCommand(registry: CommandRegistry, core: OpenACPCore):
if (bypassValue && modeConfig) {
try {
const targetValue = wantOn ? bypassValue : nonBypassDefault!
await session.setConfigOption(modeConfig.id, { type: 'select', value: targetValue })
core.eventBus.emit(BusEvent.SESSION_CONFIG_CHANGED, { sessionId: session.id })
const response = await session.agentInstance.setConfigOption(
modeConfig.id,
{ type: 'select', value: targetValue },
)
if (response.configOptions) {
session.configOptions = response.configOptions as ConfigOption[]
}
core.eventBus.emit('session:configChanged', { sessionId: session.id })
return {
type: 'text',
text: wantOn
@ -219,11 +234,7 @@ function registerDangerousCommand(registry: CommandRegistry, core: OpenACPCore):
: '🔐 **Bypass Permissions disabled** — you will be asked to approve risky actions.',
} satisfies CommandResponse
} catch (err) {
log.error({ err }, 'setConfigOption failed (bypass toggle)')
const msg = err instanceof Error ? err.message
: typeof err === 'object' && err !== null && typeof (err as any).message === 'string'
? (err as any).message
: String(err)
const msg = err instanceof Error ? err.message : String(err)
return { type: 'error', message: `Could not toggle bypass: ${msg}` } satisfies CommandResponse
}
}
@ -233,7 +244,7 @@ function registerDangerousCommand(registry: CommandRegistry, core: OpenACPCore):
await core.sessionManager.patchRecord(session.id, {
clientOverrides: { ...session.clientOverrides },
})
core.eventBus.emit(BusEvent.SESSION_CONFIG_CHANGED, { sessionId: session.id })
core.eventBus.emit('session:configChanged', { sessionId: session.id })
return {
type: 'text',
text: wantOn

View File

@ -78,6 +78,19 @@ export function registerSessionCommands(registry: CommandRegistry, _core: unknow
},
})
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.' }
},
})
registry.register({
name: 'newchat',
description: 'New chat, same agent & workspace',

View File

@ -36,7 +36,6 @@ export function registerSwitchCommands(registry: CommandRegistry, _core: unknown
// /switch <agentName> → direct switch
if (raw) {
const droppedCount = session.queueDepth
if (session.promptRunning) {
await session.abortPrompt()
}
@ -44,8 +43,7 @@ export function registerSwitchCommands(registry: CommandRegistry, _core: unknown
try {
const { resumed } = await core.switchSessionAgent(session.id, raw)
const status = resumed ? 'resumed' : 'new session'
const droppedNote = droppedCount > 0 ? ` (${droppedCount} queued prompt${droppedCount > 1 ? 's' : ''} cleared)` : ''
return { type: 'text', text: `✅ Switched to ${raw} (${status})${droppedNote}` } satisfies CommandResponse
return { type: 'text', text: `✅ Switched to ${raw} (${status})` } satisfies CommandResponse
} catch (err: any) {
return { type: 'error', message: `Failed to switch agent: ${err.message || err}` } satisfies CommandResponse
}

View File

@ -0,0 +1,86 @@
import { describe, it, expect, afterEach } from "vitest";
import { ConfigManager } from "../config.js";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
describe("Config env var overrides — Slack", () => {
const tmpDir = path.join(os.tmpdir(), `openacp-test-${Date.now()}`);
const configPath = path.join(tmpDir, "config.json");
afterEach(() => {
delete process.env.OPENACP_SLACK_BOT_TOKEN;
delete process.env.OPENACP_SLACK_APP_TOKEN;
delete process.env.OPENACP_SLACK_SIGNING_SECRET;
delete process.env.OPENACP_CONFIG_PATH;
try { fs.rmSync(tmpDir, { recursive: true }); } catch { /* ignore */ }
});
it("OPENACP_SLACK_BOT_TOKEN overrides channels.slack.botToken", async () => {
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(configPath, JSON.stringify({
channels: { slack: { enabled: true, botToken: "old-token" } },
agents: {},
defaultAgent: "claude",
}));
process.env.OPENACP_SLACK_BOT_TOKEN = "xoxb-env-override";
process.env.OPENACP_CONFIG_PATH = configPath;
const mgr = new ConfigManager();
await mgr.load();
const config = mgr.get();
expect((config.channels as any).slack.botToken).toBe("xoxb-env-override");
});
it("OPENACP_SLACK_APP_TOKEN overrides channels.slack.appToken", async () => {
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(configPath, JSON.stringify({
channels: { slack: { enabled: true, appToken: "old-app-token" } },
agents: {},
defaultAgent: "claude",
}));
process.env.OPENACP_SLACK_APP_TOKEN = "xapp-1-env-override";
process.env.OPENACP_CONFIG_PATH = configPath;
const mgr = new ConfigManager();
await mgr.load();
const config = mgr.get();
expect((config.channels as any).slack.appToken).toBe("xapp-1-env-override");
});
it("OPENACP_SLACK_SIGNING_SECRET overrides channels.slack.signingSecret", async () => {
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(configPath, JSON.stringify({
channels: { slack: { enabled: true, signingSecret: "old-secret" } },
agents: {},
defaultAgent: "claude",
}));
process.env.OPENACP_SLACK_SIGNING_SECRET = "new-secret-from-env";
process.env.OPENACP_CONFIG_PATH = configPath;
const mgr = new ConfigManager();
await mgr.load();
const config = mgr.get();
expect((config.channels as any).slack.signingSecret).toBe("new-secret-from-env");
});
it("creates channels.slack path if it doesn't exist in config", async () => {
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(configPath, JSON.stringify({
channels: {},
agents: {},
defaultAgent: "claude",
}));
process.env.OPENACP_SLACK_BOT_TOKEN = "xoxb-new";
process.env.OPENACP_CONFIG_PATH = configPath;
const mgr = new ConfigManager();
await mgr.load();
const config = mgr.get();
expect((config.channels as any).slack.botToken).toBe("xoxb-new");
});
});

View File

@ -2,17 +2,117 @@ import { describe, it, expect } from 'vitest'
import { applyMigrations } from '../config-migrations.js'
describe('Config Migrations', () => {
describe('migration: add-instance-name', () => {
it('adds instanceName "Main" when missing', () => {
const raw: Record<string, unknown> = { defaultAgent: 'claude' }
describe('migration: add tunnel section', () => {
it('adds tunnel with defaults when missing', () => {
const raw: Record<string, unknown> = { channels: {}, agents: {}, defaultAgent: 'claude' }
applyMigrations(raw)
expect(raw.instanceName).toBe('Main')
expect(raw.tunnel).toEqual({
enabled: true,
port: 3100,
provider: 'openacp',
options: {},
storeTtlMinutes: 60,
auth: { enabled: false },
})
})
it('does not overwrite existing instanceName', () => {
const raw: Record<string, unknown> = { defaultAgent: 'claude', instanceName: 'My Instance' }
it('does not overwrite existing tunnel config', () => {
const tunnel = { enabled: false, port: 9999, provider: 'ngrok', options: {}, storeTtlMinutes: 30, auth: { enabled: true } }
const raw: Record<string, unknown> = {
channels: {},
agents: {},
defaultAgent: 'claude',
tunnel,
}
applyMigrations(raw)
expect(raw.instanceName).toBe('My Instance')
expect(raw.tunnel).toEqual(tunnel)
})
})
describe('migration: fix agent commands', () => {
it('migrates "claude" command to "claude-agent-acp"', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude', args: [] } },
defaultAgent: 'claude',
}
applyMigrations(raw)
expect((raw.agents as any).claude.command).toBe('claude-agent-acp')
})
it('migrates "claude-code" command to "claude-agent-acp"', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude-code', args: [] } },
defaultAgent: 'claude',
}
applyMigrations(raw)
expect((raw.agents as any).claude.command).toBe('claude-agent-acp')
})
it('leaves "claude-agent-acp" untouched', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude-agent-acp', args: [] } },
defaultAgent: 'claude',
}
applyMigrations(raw)
expect((raw.agents as any).claude.command).toBe('claude-agent-acp')
})
it('does not touch non-claude agents', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { codex: { command: 'codex', args: ['--acp'] } },
defaultAgent: 'codex',
}
applyMigrations(raw)
expect((raw.agents as any).codex.command).toBe('codex')
})
})
describe('applyMigrations', () => {
it('applies all migrations and mutates config in place', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude', args: [] } },
defaultAgent: 'claude',
}
const { changed } = applyMigrations(raw)
expect(changed).toBe(true)
expect(raw.tunnel).toBeDefined()
expect((raw.agents as any).claude.command).toBe('claude-agent-acp')
})
it('returns changed=false when no migrations needed', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude-agent-acp', args: [] } },
defaultAgent: 'claude',
tunnel: { enabled: true, port: 3100, provider: 'openacp', options: {}, storeTtlMinutes: 60, auth: { enabled: false } },
instanceName: 'Main',
}
const { changed } = applyMigrations(raw)
expect(changed).toBe(false)
})
it('does not pollute config with changed property', () => {
const raw: Record<string, unknown> = {
channels: {},
agents: { claude: { command: 'claude', args: [] } },
defaultAgent: 'claude',
}
applyMigrations(raw)
expect(raw).not.toHaveProperty('changed')
})
})
})

View File

@ -11,8 +11,10 @@ import type { Config } from '../config.js'
describe('getConfigValue', () => {
const config = {
channels: { telegram: { enabled: true, botToken: 'tok' } },
defaultAgent: 'claude',
workspace: { baseDir: '~/workspace' },
security: { allowedUserIds: ['user1'], maxConcurrentSessions: 10, sessionTimeoutMinutes: 60 },
logging: { level: 'info' },
sessionStore: { ttlDays: 30 },
} as unknown as Config
@ -25,12 +27,20 @@ describe('getConfigValue', () => {
expect(getConfigValue(config, 'workspace.baseDir')).toBe('~/workspace')
})
it('gets deeply nested value', () => {
expect(getConfigValue(config, 'security.maxConcurrentSessions')).toBe(10)
})
it('gets value from channel config', () => {
expect(getConfigValue(config, 'channels.telegram.enabled')).toBe(true)
})
it('returns undefined for non-existent top-level key', () => {
expect(getConfigValue(config, 'nonexistent')).toBeUndefined()
})
it('returns undefined for non-existent nested key', () => {
expect(getConfigValue(config, 'logging.nonexistent')).toBeUndefined()
expect(getConfigValue(config, 'security.nonexistent')).toBeUndefined()
})
it('returns undefined when intermediate is not an object', () => {
@ -41,6 +51,12 @@ describe('getConfigValue', () => {
expect(getConfigValue(config, 'a.b.c.d.e')).toBeUndefined()
})
it('returns array values', () => {
const result = getConfigValue(config, 'security.allowedUserIds')
expect(Array.isArray(result)).toBe(true)
expect(result).toEqual(['user1'])
})
it('returns object values', () => {
const result = getConfigValue(config, 'workspace')
expect(result).toEqual({ baseDir: '~/workspace' })
@ -95,7 +111,7 @@ describe('isHotReloadable', () => {
})
it('returns false for non-hot-reloadable field', () => {
expect(isHotReloadable('nonexistent.field')).toBe(false)
expect(isHotReloadable('tunnel.enabled')).toBe(false)
})
it('returns false for unknown field', () => {

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