Compare commits
367 Commits
fix/sessio
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb251ae462 | ||
|
|
33503182b4 | ||
|
|
777735bde8 | ||
|
|
7ab215f801 | ||
|
|
9e83103574 | ||
|
|
b59456115f | ||
|
|
35522d386c | ||
|
|
1ff14957ad | ||
|
|
952ad698c9 | ||
|
|
2166d2db6a | ||
|
|
91c2a672d5 | ||
|
|
7b81fa40f7 | ||
|
|
69f9d0f2c9 | ||
|
|
e8702a15fb | ||
|
|
191cabe2f9 | ||
|
|
bbc5b275bc | ||
|
|
44b658e3db | ||
|
|
5fb0b60355 | ||
|
|
e521b372ee | ||
|
|
2084c587e2 | ||
|
|
83f349c47e | ||
|
|
9f2abea16d | ||
|
|
85fdbf9bf1 | ||
|
|
b893fb7062 | ||
|
|
24ed74a699 | ||
|
|
e2759b97ce | ||
|
|
a9fbdc8340 | ||
|
|
8dd6cfd8c3 | ||
|
|
06150713ac | ||
|
|
23aa5d0459 | ||
|
|
eb07e68aa4 | ||
|
|
2e01b28330 | ||
|
|
0aef31ce74 | ||
|
|
8073235299 | ||
|
|
aa5f25b974 | ||
|
|
3d57f94e8e | ||
|
|
30b868995b | ||
|
|
33af0a98c7 | ||
|
|
39037f560c | ||
|
|
a313b90462 | ||
|
|
93d85742a1 | ||
|
|
5b132d1b50 | ||
|
|
15e0e1ef1f | ||
|
|
e718e2d5f2 | ||
|
|
4386cd0b19 | ||
|
|
215c64c2cd | ||
|
|
4495fdbf0b | ||
|
|
24fd15f7f9 | ||
|
|
9ec2dddb4a | ||
|
|
8084061c3e | ||
|
|
abe0d8ed29 | ||
|
|
1327f0f470 | ||
|
|
0373225f55 | ||
|
|
c6cb7ff5f7 | ||
|
|
15bc3ae4bb | ||
|
|
3b69880c5d | ||
|
|
67720e2661 | ||
|
|
446071b0e9 | ||
|
|
b395d30919 | ||
|
|
e83a3b08e7 | ||
|
|
c542f8e837 | ||
|
|
4c16b59d2f | ||
|
|
506f04be98 | ||
|
|
65fbf5469f | ||
|
|
1644f7b888 | ||
|
|
d9e0a90be7 | ||
|
|
b1eae11d1e | ||
|
|
7247cf28c5 | ||
|
|
3e1dd3d913 | ||
|
|
e5eb22072f | ||
|
|
e0a4ebbc72 | ||
|
|
3e7da2ad7d | ||
|
|
9dca3462d2 | ||
|
|
1a98d0c197 | ||
|
|
e0c6ae55f0 | ||
|
|
897b73354f | ||
|
|
35b2ff9626 | ||
|
|
68fe7b1e96 | ||
|
|
0756c87b0d | ||
|
|
d40199799c | ||
|
|
e96777bc2d | ||
|
|
ad6b1d9614 | ||
|
|
4e6425e414 | ||
|
|
a60e00d18a | ||
|
|
c16f4170a2 | ||
|
|
12e7af8da2 | ||
|
|
f9fd4d41c2 | ||
|
|
914ac48eef | ||
|
|
2075fc4819 | ||
|
|
88138e29ce | ||
|
|
9f4f688961 | ||
|
|
6baf41f0b6 | ||
|
|
71c8a3478b | ||
|
|
2f9a9c4358 | ||
|
|
c1482b19c4 | ||
|
|
faf6286e12 | ||
|
|
d082b35f55 | ||
|
|
8a0b6166a1 | ||
|
|
4c79487d7c | ||
|
|
2b59db122e | ||
|
|
976e4ded91 | ||
|
|
e0f481bc9a | ||
|
|
3d584f7ed4 | ||
|
|
29eb319400 | ||
|
|
0aab4e63e8 | ||
|
|
179f36442d | ||
|
|
48250b7263 | ||
|
|
4d9e066995 | ||
|
|
5668f6f6ca | ||
|
|
8b24b8921e | ||
|
|
416b78fc6e | ||
|
|
3ada6cbe13 | ||
|
|
10836a33c6 | ||
|
|
63a30d3ef4 | ||
|
|
f3230dbc92 | ||
|
|
0f93c9e2ed | ||
|
|
1b58423755 | ||
|
|
a88f69e470 | ||
|
|
892b87a039 | ||
|
|
a276154742 | ||
|
|
3281976826 | ||
|
|
007012fef1 | ||
|
|
d6a1321784 | ||
|
|
4371823763 | ||
|
|
3f501a373c | ||
|
|
f45dc494f6 | ||
|
|
027e0f99a6 | ||
|
|
7b206f8124 | ||
|
|
71682f72d3 | ||
|
|
bb7de274d2 | ||
|
|
6f77aed353 | ||
|
|
4518267bfb | ||
|
|
c873230761 | ||
|
|
565a70b69c | ||
|
|
89c6ab02b1 | ||
|
|
4a2e574e2c | ||
|
|
8273dcc2ba | ||
|
|
e1f90feacd | ||
|
|
4561a602c0 | ||
|
|
33d4f70342 | ||
|
|
50255e9743 | ||
|
|
25616f7d68 | ||
|
|
91ad6c7c81 | ||
|
|
75ae2e36fd | ||
|
|
1d8b2adc8b | ||
|
|
cc5625d5ee | ||
|
|
9ea46457de | ||
|
|
0b17f88285 | ||
|
|
5b7fee0e92 | ||
|
|
d33f975ce7 | ||
|
|
69d73c981b | ||
|
|
25e5eb85cd | ||
|
|
e3f017e05d | ||
|
|
4075d87f6a | ||
|
|
4564d392e2 | ||
|
|
38ca66f36b | ||
|
|
608a24ceff | ||
|
|
7b91ca2203 | ||
|
|
aec7cbd0f8 | ||
|
|
eae34bbdb7 | ||
|
|
78d844ee64 | ||
|
|
ceecbced9a | ||
|
|
e3366024f2 | ||
|
|
a5d74b0e34 | ||
|
|
23303c80b7 | ||
|
|
9834029f7e | ||
|
|
62f2462d93 | ||
|
|
58d08a13b6 | ||
|
|
de4cb590ab | ||
|
|
97cc32a9d6 | ||
|
|
c42b2cf7f0 | ||
|
|
17d14e9b01 | ||
|
|
94b5648084 | ||
|
|
be7dccb6a1 | ||
|
|
8161fe35c7 | ||
|
|
7b6c96828d | ||
|
|
1f0297cce5 | ||
|
|
ffae9763ab | ||
|
|
cff8de0213 | ||
|
|
d2509efd8c | ||
|
|
ef9c03fbee | ||
|
|
ea4a1e66c6 | ||
|
|
96b06a8206 | ||
|
|
2860b42f49 | ||
|
|
9677f623ad | ||
|
|
3fab446bbe | ||
|
|
ce9ed32a73 | ||
|
|
89c67176bc | ||
|
|
0dbaa518cf | ||
|
|
5818dbfdae | ||
|
|
8a8a80f3e9 | ||
|
|
f9e36052ad | ||
|
|
a6cf76f15e | ||
|
|
e193309e08 | ||
|
|
43c16dff4b | ||
|
|
b55aa151db | ||
|
|
f9c58cb2a2 | ||
|
|
11a9e18bb0 | ||
|
|
fdf4fba7a3 | ||
|
|
aee454f2f7 | ||
|
|
71411ca905 | ||
|
|
ee4518af2e | ||
|
|
ef9c6eabae | ||
|
|
23f2d295fd | ||
|
|
7b2f0f78c1 | ||
|
|
eeb6a7d923 | ||
|
|
18cc04d3f3 | ||
|
|
5329803b86 | ||
|
|
aaf82863bb | ||
|
|
62cf9bd2bf | ||
|
|
46350a95c5 | ||
|
|
adbe268209 | ||
|
|
e90fedcef8 | ||
|
|
9720330085 | ||
|
|
ad83f7897c | ||
|
|
637d326ea8 | ||
|
|
fa071dc5c4 | ||
|
|
fc69a2f122 | ||
|
|
b1840d538d | ||
|
|
f33f89223a | ||
|
|
3919d29c12 | ||
|
|
8a9a724b15 | ||
|
|
6e0cde1e41 | ||
|
|
ae6a904789 | ||
|
|
7f75153a4c | ||
|
|
a8217ea535 | ||
|
|
2bb70d0ac9 | ||
|
|
e8a0242e72 | ||
|
|
ace8d675d8 | ||
|
|
59c76a080b | ||
|
|
07daa1d432 | ||
|
|
f9bcb34979 | ||
|
|
cb7e587382 | ||
|
|
78495c7856 | ||
|
|
8b9b7ffc36 | ||
|
|
93c5aea626 | ||
|
|
6b4867854d | ||
|
|
4480389b65 | ||
|
|
e300e7d605 | ||
|
|
e359613e07 | ||
|
|
1f071db03a | ||
|
|
eea6e9a4fe | ||
|
|
ed3256a283 | ||
|
|
d9b93b3542 | ||
|
|
378b97d3d0 | ||
|
|
73b6d58b20 | ||
|
|
0a91c37f28 | ||
|
|
36cdf4ce1c | ||
|
|
92ac54a3c3 | ||
|
|
377e84c6f3 | ||
|
|
5179d3334d | ||
|
|
aebd7fa8d8 | ||
|
|
3c74ec0feb | ||
|
|
32132a801e | ||
|
|
a031d21f6e | ||
|
|
b92e542a30 | ||
|
|
d676faadc7 | ||
|
|
3d39d1d811 | ||
|
|
4648ae50a1 | ||
|
|
c3e4e32a9b | ||
|
|
f731f30b9a | ||
|
|
2a72a1ee38 | ||
|
|
3526752bb3 | ||
|
|
cea1009e6c | ||
|
|
d180967d17 | ||
|
|
87cec6734a | ||
|
|
81d2184f4d | ||
|
|
79aee6960f | ||
|
|
6743e10af3 | ||
|
|
3a01a50949 | ||
|
|
72f99a3a62 | ||
|
|
bd5341995e | ||
|
|
26b78cf28f | ||
|
|
3d36553cac | ||
|
|
8255a41eec | ||
|
|
ff29e9e29f | ||
|
|
2d09b32b96 | ||
|
|
a904c14686 | ||
|
|
f321f44bc8 | ||
|
|
71270591b4 | ||
|
|
bf0b709f78 | ||
|
|
967d4cfece | ||
|
|
0def26e882 | ||
|
|
f4b2943316 | ||
|
|
6d32160d4c | ||
|
|
bde5a1071e | ||
|
|
84c4a0f438 | ||
|
|
ca4e789925 | ||
|
|
537cc37b1a | ||
|
|
6d631d3966 | ||
|
|
2e3c1f7007 | ||
|
|
7d263a0e7e | ||
|
|
013fe12e19 | ||
|
|
fc41d74ab1 | ||
|
|
cc3897764d | ||
|
|
077a254ba4 | ||
|
|
dbc4d3fbfc | ||
|
|
bcaa61b969 | ||
|
|
3a45d8a209 | ||
|
|
eb09ffd6d8 | ||
|
|
ded47458a7 | ||
|
|
695dd1c6fe | ||
|
|
b5d24bce5a | ||
|
|
e558b477e4 | ||
|
|
90d637348e | ||
|
|
56e79875fe | ||
|
|
0c302331cc | ||
|
|
9c74a3e9e0 | ||
|
|
7b768c717d | ||
|
|
a2ac1d2ac4 | ||
|
|
709adad68f | ||
|
|
a9d82ebd2f | ||
|
|
51ead8c94b | ||
|
|
e49d6993b1 | ||
|
|
3cf4d852f6 | ||
|
|
943f8ab26c | ||
|
|
16f92a7e27 | ||
|
|
16a40c7993 | ||
|
|
673e914b28 | ||
|
|
466221a124 | ||
|
|
3caaa5c397 | ||
|
|
672b7635ca | ||
|
|
46fadb72fe | ||
|
|
09627a0eeb | ||
|
|
e919bb7223 | ||
|
|
f57ece81ae | ||
|
|
f98647eaa3 | ||
|
|
fca3e82737 | ||
|
|
64ef8f83ab | ||
|
|
4259ba76ea | ||
|
|
b15af4abe0 | ||
|
|
78033e81c1 | ||
|
|
5dba1746a5 | ||
|
|
fdf9ae990f | ||
|
|
7fe7869cad | ||
|
|
d3a690294b | ||
|
|
3a254e58c7 | ||
|
|
5dfac08605 | ||
|
|
27c4229f55 | ||
|
|
fbec2ce94f | ||
|
|
2caeb4f750 | ||
|
|
481a0e3921 | ||
|
|
b7bab6703b | ||
|
|
e8aa355516 | ||
|
|
a843413c65 | ||
|
|
3af41aec5b | ||
|
|
9b8239373a | ||
|
|
09113d5a21 | ||
|
|
ad52f755e0 | ||
|
|
03f150613f | ||
|
|
485c64b5de | ||
|
|
3357507160 | ||
|
|
cbc3214b13 | ||
|
|
b9120ba82e | ||
|
|
f35b6d130b | ||
|
|
b4d78d511f | ||
|
|
17f6a4ec92 | ||
|
|
0fed71db58 | ||
|
|
602ea7b620 | ||
|
|
875a1a2b54 | ||
|
|
ae7a7b726b | ||
|
|
d78c1454c2 | ||
|
|
d361c2f69b | ||
|
|
e5bf0f39a1 | ||
|
|
77f658121d | ||
|
|
f9f14749b5 | ||
|
|
133867c84e |
79
.github/ISSUE_TEMPLATE/adapter_request.yml
vendored
Normal file
79
.github/ISSUE_TEMPLATE/adapter_request.yml
vendored
Normal file
@ -0,0 +1,79 @@
|
||||
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
|
||||
104
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
104
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,104 @@
|
||||
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
|
||||
11
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
11
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
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.
|
||||
75
.github/ISSUE_TEMPLATE/documentation.yml
vendored
Normal file
75
.github/ISSUE_TEMPLATE/documentation.yml
vendored
Normal file
@ -0,0 +1,75 @@
|
||||
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
|
||||
74
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
74
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
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
|
||||
59
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
59
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@ -0,0 +1,59 @@
|
||||
## 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
2
.gitignore
vendored
@ -1,3 +1,5 @@
|
||||
.DS_Store
|
||||
|
||||
# References (external/third-party code)
|
||||
references/
|
||||
node_modules/
|
||||
|
||||
@ -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.
|
||||
|
||||
- 18 middleware hook points (message:incoming, agent:beforePrompt, permission:beforeRequest, etc.)
|
||||
- 19 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
|
||||
|
||||
- **Forum topics** (Telegram): Each session gets its own topic
|
||||
- **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
|
||||
|
||||
|
||||
53
CODE_OF_CONDUCT.md
Normal file
53
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,53 @@
|
||||
# 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).
|
||||
167
CONTRIBUTING.md
Normal file
167
CONTRIBUTING.md
Normal file
@ -0,0 +1,167 @@
|
||||
# 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).
|
||||
134
README.md
134
README.md
@ -1,3 +1,5 @@
|
||||
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
|
||||
@ -12,7 +14,9 @@ Send a message. The agent writes code. You see everything — in real time.
|
||||
[](https://www.npmjs.com/package/@openacp/cli)
|
||||
[](https://x.com/openacp_ai)
|
||||
|
||||
[Documentation](https://openacp.gitbook.io/docs) · [Quick Start](#quick-start) · [Features](#features) · [Agents](#supported-agents) · [Contributing](https://openacp.gitbook.io/docs/extending/contributing)
|
||||
[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%" />
|
||||
|
||||
</div>
|
||||
|
||||
@ -34,42 +38,85 @@ 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" /><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>
|
||||
<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>
|
||||
</tr>
|
||||
<tr>
|
||||
<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>
|
||||
<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>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
## Quick Start
|
||||
## Installation
|
||||
|
||||
**Requirements:** Node.js 20+ (the installer handles this for you)
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
# macOS / Linux
|
||||
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
# Windows
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
> Works on Debian/Ubuntu, Fedora/RHEL, Arch, and other distros. Also supports WSL (Windows Subsystem for Linux).
|
||||
|
||||
### Windows
|
||||
|
||||
Open PowerShell and run:
|
||||
|
||||
```powershell
|
||||
powershell -c "irm https://raw.githubusercontent.com/Open-ACP/OpenACP/main/scripts/install.ps1 | iex"
|
||||
```
|
||||
|
||||
Works on macOS, Linux & Windows. Installs Node.js (if needed) and everything else for you.
|
||||
> Requires PowerShell 5.1+ (built into Windows 10/11).
|
||||
|
||||
<details>
|
||||
<summary>Or install via npm</summary>
|
||||
### Manual install via npm
|
||||
|
||||
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!
|
||||
```
|
||||
|
||||
</details>
|
||||
---
|
||||
|
||||
The interactive setup wizard walks you through everything:
|
||||
After installation, the **interactive setup wizard** walks you through everything:
|
||||
|
||||
1. Choose your platform (Telegram, Discord, Slack, or multiple)
|
||||
2. Connect your bot (token validation + auto-detection)
|
||||
@ -133,7 +180,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](https://github.com/tao12345666333/amp-acp) | binary | The frontier coding agent |
|
||||
| Amp | 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 |
|
||||
@ -184,6 +231,59 @@ 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">
|
||||
@ -196,11 +296,7 @@ openacp tunnel list
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome contributions! See the [contributing guide](https://openacp.gitbook.io/docs/extending/contributing) for development setup, testing conventions, and PR process.
|
||||
|
||||
## Follow Us
|
||||
|
||||
[](https://x.com/openacp_ai)
|
||||
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).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@ -4,6 +4,28 @@ All commands are invoked as `openacp <command> [subcommand] [options]`. Every co
|
||||
|
||||
---
|
||||
|
||||
## JSON Output
|
||||
|
||||
Many commands accept a `--json` flag for machine-readable output. When `--json` is passed:
|
||||
|
||||
- Output is a single line of valid JSON on stdout
|
||||
- Exit code `0` for success, non-zero for errors
|
||||
- All progress indicators and ANSI codes are suppressed
|
||||
|
||||
**Success envelope (exit 0):**
|
||||
```json
|
||||
{ "success": true, "data": { ... } }
|
||||
```
|
||||
|
||||
**Error envelope (exit non-zero):**
|
||||
```json
|
||||
{ "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable description" } }
|
||||
```
|
||||
|
||||
Commands that support `--json` are noted in their options tables below.
|
||||
|
||||
---
|
||||
|
||||
## adopt
|
||||
|
||||
Transfers an existing external agent session into OpenACP so it appears as a messaging thread. Requires a running daemon.
|
||||
@ -19,12 +41,19 @@ openacp adopt <agent> <session_id> [--cwd <path>] [--channel <name>]
|
||||
|---|---|
|
||||
| `--cwd <path>` | Working directory for the session (default: current directory) |
|
||||
| `--channel <name>` | Target channel adapter, e.g. `telegram`, `discord` (default: first registered) |
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**Examples**
|
||||
```bash
|
||||
openacp adopt claude abc123-def456
|
||||
openacp adopt claude abc123 --cwd /path/to/project
|
||||
openacp adopt claude abc123 --channel discord
|
||||
openacp adopt claude abc123 --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "sessionId": "...", "threadId": "...", "agent": "claude", "status": "active" }
|
||||
```
|
||||
|
||||
---
|
||||
@ -58,6 +87,12 @@ Lists all installed agents and agents available to install from the registry.
|
||||
**Example**
|
||||
```bash
|
||||
openacp agents
|
||||
openacp agents --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "agents": [{ "key": "claude", "name": "Claude Code", "version": "1.0.0", "distribution": "npm", "description": "...", "installed": true, "available": true, "missingDeps": [] }] }
|
||||
```
|
||||
|
||||
### agents install
|
||||
@ -65,16 +100,23 @@ openacp agents
|
||||
Installs an agent from the ACP Registry. Automatically installs the handoff integration if the agent supports it.
|
||||
|
||||
```
|
||||
openacp agents install <name> [--force]
|
||||
openacp agents install <name> [--force] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--force` | Reinstall even if already installed |
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp agents install claude
|
||||
openacp agents install gemini --force
|
||||
openacp agents install claude --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "key": "claude", "version": "1.0.0", "installed": true }
|
||||
```
|
||||
|
||||
### agents uninstall
|
||||
@ -82,11 +124,21 @@ openacp agents install gemini --force
|
||||
Removes an installed agent and its handoff integration (if any).
|
||||
|
||||
```
|
||||
openacp agents uninstall <name>
|
||||
openacp agents uninstall <name> [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp agents uninstall gemini
|
||||
openacp agents uninstall gemini --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "key": "gemini", "uninstalled": true }
|
||||
```
|
||||
|
||||
### agents info
|
||||
@ -94,12 +146,22 @@ openacp agents uninstall gemini
|
||||
Shows version, distribution type, command, setup steps, and installation status for an agent.
|
||||
|
||||
```
|
||||
openacp agents info <name>
|
||||
openacp agents info <name> [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp agents info cursor
|
||||
openacp agents info claude
|
||||
openacp agents info claude --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "key": "claude", "name": "Claude Code", "version": "1.0.0", "distribution": "npm", "description": "...", "installed": true, "binaryPath": "/usr/local/bin/claude", "command": "claude", "registryId": "claude" }
|
||||
```
|
||||
|
||||
### agents run
|
||||
@ -132,9 +194,11 @@ openacp agents refresh
|
||||
|
||||
Interacts with a running OpenACP daemon over the local REST API. Requires a running daemon (`openacp start`).
|
||||
|
||||
All `api` subcommands support `--json` for machine-readable output.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp api <subcommand> [args]
|
||||
openacp api <subcommand> [args] [--json]
|
||||
```
|
||||
|
||||
### api cancel
|
||||
@ -327,12 +391,18 @@ openacp config set <key> <value>
|
||||
|
||||
`openacp config` (no args) opens an interactive terminal editor. When the daemon is running, changes are applied live via the API; otherwise the config file is edited directly.
|
||||
|
||||
`openacp config set` applies a single value by dot-notation path. Values are JSON-parsed if possible, otherwise treated as strings.
|
||||
`openacp config set` applies a single value by dot-notation path. Values are JSON-parsed if possible, otherwise treated as strings. Supports `--json` for scripted use.
|
||||
|
||||
```bash
|
||||
openacp config set defaultAgent claude
|
||||
openacp config set security.maxConcurrentSessions 5
|
||||
openacp config set channels.telegram.botToken "123:ABC"
|
||||
openacp config set defaultAgent gemini --json
|
||||
```
|
||||
|
||||
**JSON output for `config set`** (`data` shape):
|
||||
```json
|
||||
{ "path": "defaultAgent", "value": "gemini", "needsRestart": false }
|
||||
```
|
||||
|
||||
---
|
||||
@ -343,12 +413,21 @@ Runs system diagnostics. Checks config validity, agent availability, dependencie
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp doctor [--dry-run]
|
||||
openacp doctor [--dry-run] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--dry-run` | Report issues only; do not apply any fixes |
|
||||
| `--json` | Output result as JSON (implies `--dry-run`; always exits 0 — check `summary.failed` for health) |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{
|
||||
"categories": [{ "name": "Config", "results": [{ "status": "pass", "message": "Config is valid" }] }],
|
||||
"summary": { "passed": 5, "warnings": 1, "failed": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@ -358,12 +437,22 @@ Installs a plugin from npm into `~/.openacp/plugins/`. Supports built-in plugins
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp install <package>[@version]
|
||||
openacp install <package>[@version] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp install @openacp/adapter-discord
|
||||
openacp install @myorg/translator@1.2.0
|
||||
openacp install @openacp/adapter-discord --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "plugin": "@openacp/adapter-discord", "version": "1.0.0", "installed": true }
|
||||
```
|
||||
|
||||
This is an alias for `openacp plugin add`. See [plugin install](#plugin-install) for details.
|
||||
@ -383,6 +472,7 @@ openacp integrate <agent> --uninstall
|
||||
```bash
|
||||
openacp integrate claude
|
||||
openacp integrate claude --uninstall
|
||||
openacp integrate opencode
|
||||
```
|
||||
|
||||
---
|
||||
@ -448,15 +538,25 @@ Installs a plugin package. Works with both built-in plugins and community plugin
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp plugin add <package>[@version]
|
||||
openacp plugin install <package>[@version]
|
||||
openacp plugin add <package>[@version] [--json]
|
||||
openacp plugin install <package>[@version] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**Examples**
|
||||
```bash
|
||||
openacp plugin add @openacp/adapter-discord
|
||||
openacp plugin add @myorg/translator@1.2.0
|
||||
openacp plugin install my-plugin
|
||||
openacp plugin add @openacp/adapter-discord --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "plugin": "@openacp/adapter-discord", "version": "1.0.0", "installed": true }
|
||||
```
|
||||
|
||||
Community plugins are installed via `npm install` into `~/.openacp/plugins/node_modules/`. The plugin's `install()` hook is called if defined.
|
||||
@ -485,14 +585,24 @@ Enables or disables an installed plugin without removing it. Disabled plugins ar
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp plugin enable <name>
|
||||
openacp plugin disable <name>
|
||||
openacp plugin enable <name> [--json]
|
||||
openacp plugin disable <name> [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**Examples**
|
||||
```bash
|
||||
openacp plugin disable @myorg/translator
|
||||
openacp plugin enable @myorg/translator
|
||||
openacp plugin enable @myorg/translator --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "plugin": "@myorg/translator", "enabled": true }
|
||||
```
|
||||
|
||||
---
|
||||
@ -503,9 +613,13 @@ Generates access links for connecting app clients to a running OpenACP instance.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp remote
|
||||
openacp remote [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON (no QR code printed) |
|
||||
|
||||
The generated link includes a single-use access code valid for 30 minutes. The app exchanges this code for a JWT token on first use.
|
||||
|
||||
**Example output**
|
||||
@ -517,6 +631,11 @@ App: openacp://connect?host=abc.trycloudflare.com&code=xyz123
|
||||
[QR code]
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "code": "xyz123", "name": "my-instance", "role": "owner", "expiresAt": "2026-04-02T13:00:00Z", "urls": { "local": "http://127.0.0.1:21420", "tunnel": "https://abc.trycloudflare.com", "app": "openacp://connect?host=abc.trycloudflare.com&code=xyz123" } }
|
||||
```
|
||||
|
||||
See [App Connectivity](../features/app-connectivity.md) for the full guide.
|
||||
|
||||
---
|
||||
@ -527,7 +646,16 @@ Lists all plugins installed in `~/.openacp/plugins/`.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp plugins
|
||||
openacp plugins [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "plugins": [{ "name": "@openacp/adapter-discord", "version": "1.0.0", "enabled": true, "source": "npm", "description": "Discord adapter" }] }
|
||||
```
|
||||
|
||||
---
|
||||
@ -547,10 +675,27 @@ Prompts for confirmation before proceeding.
|
||||
|
||||
## restart
|
||||
|
||||
There is no standalone `restart` command. Use `openacp api restart` to restart a running daemon, or stop and start it manually:
|
||||
Restarts the daemon. By default uses the same run mode as configured; use `--foreground` or `--daemon` to override.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp restart [--foreground | --daemon] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--foreground` | Restart in foreground mode (not compatible with `--json`) |
|
||||
| `--daemon` | Restart as background daemon |
|
||||
| `--json` | Output result as JSON (always uses daemon mode) |
|
||||
|
||||
```bash
|
||||
openacp stop && openacp start
|
||||
openacp restart
|
||||
openacp restart --daemon --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "pid": 12345, "instanceId": "global", "dir": "/Users/alice/.openacp" }
|
||||
```
|
||||
|
||||
---
|
||||
@ -575,6 +720,12 @@ openacp start [options]
|
||||
| `--dir <path>` | Use a specific instance directory |
|
||||
| `--name <id>` | Give the instance a name |
|
||||
| `--from <source>` | Clone settings from an existing instance |
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "pid": 12345, "instanceId": "global", "dir": "/Users/alice/.openacp" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@ -584,12 +735,24 @@ Shows whether the OpenACP daemon is running and its PID.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp status [--all]
|
||||
openacp status [--all] [--id <id>] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--all` | Show status of all registered instances, not just the current one |
|
||||
| `--id <id>` | Show status of a specific instance |
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape — all instances):
|
||||
```json
|
||||
{ "instances": [{ "id": "global", "name": "my-instance", "status": "running", "pid": 12345, "dir": "/Users/alice/.openacp", "mode": "daemon", "channels": ["telegram"], "apiPort": 21420, "tunnelPort": null }] }
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape — single instance with `--id`):
|
||||
```json
|
||||
{ "id": "global", "name": "my-instance", "status": "running", "pid": 12345, "dir": "/Users/alice/.openacp", "mode": "daemon", "channels": ["telegram"], "apiPort": 21420, "tunnelPort": null }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@ -599,7 +762,16 @@ Sends a stop signal to the running daemon.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp stop
|
||||
openacp stop [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "stopped": true, "pid": 12345 }
|
||||
```
|
||||
|
||||
---
|
||||
@ -618,12 +790,22 @@ openacp tunnel <subcommand> [args]
|
||||
Creates a tunnel to a local port.
|
||||
|
||||
```
|
||||
openacp tunnel add <port> [--label <name>] [--session <id>]
|
||||
openacp tunnel add <port> [--label <name>] [--session <id>] [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp tunnel add 3000
|
||||
openacp tunnel add 8080 --label "dev server"
|
||||
openacp tunnel add 3000 --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "port": 3000, "publicUrl": "https://abc.trycloudflare.com" }
|
||||
```
|
||||
|
||||
### tunnel list
|
||||
@ -631,7 +813,16 @@ openacp tunnel add 8080 --label "dev server"
|
||||
Lists all active tunnels with their ports, labels, and public URLs.
|
||||
|
||||
```
|
||||
openacp tunnel list
|
||||
openacp tunnel list [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "tunnels": [{ "port": 3000, "label": "dev server", "publicUrl": "https://abc.trycloudflare.com", "status": "active" }] }
|
||||
```
|
||||
|
||||
### tunnel stop
|
||||
@ -639,7 +830,16 @@ openacp tunnel list
|
||||
Stops the tunnel for a specific local port.
|
||||
|
||||
```
|
||||
openacp tunnel stop <port>
|
||||
openacp tunnel stop <port> [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "port": 3000, "stopped": true }
|
||||
```
|
||||
|
||||
### tunnel stop-all
|
||||
@ -647,7 +847,16 @@ openacp tunnel stop <port>
|
||||
Stops all user tunnels.
|
||||
|
||||
```
|
||||
openacp tunnel stop-all
|
||||
openacp tunnel stop-all [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "stopped": true }
|
||||
```
|
||||
|
||||
---
|
||||
@ -658,11 +867,21 @@ Removes an adapter plugin.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp uninstall <package>
|
||||
openacp uninstall <package> [--json]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp uninstall @openacp/adapter-discord
|
||||
openacp uninstall @openacp/adapter-discord --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "plugin": "@openacp/adapter-discord", "uninstalled": true }
|
||||
```
|
||||
|
||||
---
|
||||
@ -699,12 +918,28 @@ The startup display also shows which instance is active (global vs. local) and p
|
||||
|
||||
---
|
||||
|
||||
## --version / -v
|
||||
## version
|
||||
|
||||
Prints the installed version.
|
||||
Prints the installed version. Also available as `--version` / `-v`.
|
||||
|
||||
**Usage**
|
||||
```
|
||||
openacp version [--json]
|
||||
openacp --version
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--json` | Output result as JSON |
|
||||
|
||||
```bash
|
||||
openacp --version
|
||||
openacp version --json
|
||||
```
|
||||
|
||||
**JSON output** (`data` shape):
|
||||
```json
|
||||
{ "version": "2026.401.1" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@ -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 18 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 19 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
|
||||
|
||||
@ -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 open in the terminal.
|
||||
1. You are working at your desk with Claude Code or OpenCode 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, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). The command installs the necessary hooks so your agent can hand off sessions to OpenACP.
|
||||
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.
|
||||
|
||||
To uninstall later:
|
||||
|
||||
@ -56,19 +56,26 @@ 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` must be installed on the machine (`brew install jq` on macOS, `apt install jq` on Linux).
|
||||
- `jq` is required only for hook-based integrations (Claude/Cursor/Gemini/Cline). OpenCode plugin integration does not require `jq`.
|
||||
|
||||
---
|
||||
|
||||
## Supported agents
|
||||
|
||||
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.
|
||||
Currently supported agents include Claude Code, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, OpenAI Codex, and others. Run `openacp integrate --list` to see the full list.
|
||||
|
||||
---
|
||||
|
||||
## Technical details
|
||||
|
||||
Handoff relies on two shell scripts installed by `openacp integrate`:
|
||||
Most handoff integrations rely on two shell scripts installed by `openacp integrate`:
|
||||
|
||||
- **Inject hook** (`openacp-inject-session.sh`) — runs as an agent hook on every conversation turn, reads the agent's session ID from the hook payload, and injects it as a context variable.
|
||||
- **Handoff script** (`openacp-handoff.sh`) — calls `openacp adopt <agent> <session_id>` to register the terminal session with the running OpenACP daemon, making it visible in the messaging platform.
|
||||
|
||||
For OpenCode, handoff is installed via a command + plugin pair under `~/.config/opencode/`:
|
||||
|
||||
- **Command** (`commands/openacp-handoff.md`) — provides `/openacp:handoff`.
|
||||
- **Plugin** (`plugins/openacp-handoff.js`) — injects current OpenCode session ID so the command can call `openacp adopt opencode <session_id>`.
|
||||
|
||||
If OpenCode is started with `--pure`, plugins are disabled and session ID injection is unavailable. In this mode, `/openacp:handoff` is not supported.
|
||||
|
||||
@ -1,6 +1,13 @@
|
||||
# Telegram Setup
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@ -26,16 +33,16 @@ This guide walks you through connecting OpenACP to Telegram. OpenACP uses a Tele
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Create a Supergroup with Topics Enabled
|
||||
## Step 2: Create a Group with Topics Enabled
|
||||
|
||||
OpenACP requires a Telegram **Supergroup** with the **Topics** feature enabled. Topics create forum-like threads — one per coding session.
|
||||
OpenACP requires a Telegram group with the **Topics** feature enabled. Topics create thread-like channels — 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. Telegram converts the group to a Supergroup automatically.
|
||||
6. Save the changes.
|
||||
|
||||
---
|
||||
|
||||
@ -58,7 +65,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 Supergroup. You need it for the config.
|
||||
The Chat ID is the unique numeric identifier for your group. You need it for the config.
|
||||
|
||||
**Option A: Use the OpenACP setup wizard (recommended)**
|
||||
|
||||
@ -110,7 +117,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 Supergroup's Chat ID — negative number starting with `-100` (Step 4) |
|
||||
| `chatId` | The group'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 |
|
||||
|
||||
@ -214,13 +221,14 @@ Environment variables take precedence over values in `config.json`.
|
||||
- Verify `enabled: true` in the config.
|
||||
- Check `~/.openacp/logs/` for error messages.
|
||||
|
||||
**"Chat is not a supergroup" error**
|
||||
- The group must be a Supergroup. Go to Group Settings and convert it if needed.
|
||||
**"Chat must be a group" error**
|
||||
- Make sure you are using a group (not a channel). Channels are not supported.
|
||||
- If the group was just created, wait a moment and try again.
|
||||
|
||||
**Topics not appearing**
|
||||
- Topics must be enabled in the group settings before OpenACP starts.
|
||||
- The bot needs **Manage Topics** admin permission.
|
||||
**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.
|
||||
|
||||
**Chat ID is not detected**
|
||||
- Make sure you sent a message in the group after adding the bot.
|
||||
|
||||
@ -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 supergroup is negative (e.g., `-1001234567890`).
|
||||
2. Confirm the chat ID in `~/.openacp/config.json` matches the group. The ID of a group is negative (e.g., `-1001234567890`).
|
||||
3. Restart OpenACP after making changes.
|
||||
|
||||
---
|
||||
@ -23,25 +23,42 @@ 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 (forum mode) are not enabled.
|
||||
**Cause:** The bot lacks administrator permissions in the group, or Topics are not enabled.
|
||||
|
||||
**Solution:**
|
||||
1. Promote the bot to administrator in the group settings.
|
||||
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**.
|
||||
2. Enable Topics: **Group Settings → Edit → Topics**.
|
||||
3. In the bot's admin settings, ensure "Manage Topics" is enabled.
|
||||
|
||||
---
|
||||
|
||||
### Topics are not created on startup
|
||||
|
||||
**Symptoms:** OpenACP starts without error but no "Notifications" or "Assistant" topics appear in the group.
|
||||
**Symptoms:** OpenACP starts but no "Notifications" or "Assistant" topics appear.
|
||||
|
||||
**Cause:** The group does not have forum/topics mode enabled, or the bot is not an admin with topic management rights.
|
||||
**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.
|
||||
|
||||
**Solution:**
|
||||
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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@ -54,7 +71,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 supergroups.
|
||||
3. If the ID looks correct, check that it is a negative integer for groups.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@ -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 forum topic. On Discord, a new thread is created in the configured channel.
|
||||
On Telegram, each session gets its own topic. On Discord, a new thread is created in the configured channel.
|
||||
|
||||
### `/newchat`
|
||||
|
||||
|
||||
BIN
docs/images/banner.jpg
Normal file
BIN
docs/images/banner.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 951 KiB |
BIN
docs/superpowers/.DS_Store
vendored
Normal file
BIN
docs/superpowers/.DS_Store
vendored
Normal file
Binary file not shown.
1896
docs/superpowers/plans/2026-03-30-conversation-history.md
Normal file
1896
docs/superpowers/plans/2026-03-30-conversation-history.md
Normal file
File diff suppressed because it is too large
Load Diff
2242
docs/superpowers/plans/2026-03-30-output-mode.md
Normal file
2242
docs/superpowers/plans/2026-03-30-output-mode.md
Normal file
File diff suppressed because it is too large
Load Diff
2468
docs/superpowers/plans/2026-04-02-cli-json-output.md
Normal file
2468
docs/superpowers/plans/2026-04-02-cli-json-output.md
Normal file
File diff suppressed because it is too large
Load Diff
936
docs/superpowers/plans/2026-04-02-instances-cli-auth-exchange.md
Normal file
936
docs/superpowers/plans/2026-04-02-instances-cli-auth-exchange.md
Normal file
@ -0,0 +1,936 @@
|
||||
# Instances CLI & Auth Exchange Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add `openacp instances list/create` CLI subcommands, extend `start --json` output with name/directory, and add `POST /api/v1/auth/exchange` + `GET /api/v1/workspace` API endpoints.
|
||||
|
||||
**Architecture:** New `instances.ts` CLI command follows existing command patterns (`cmdStatus`, `cmdStart`). Auth exchange adds one route to existing `auth.ts`. Workspace endpoint is a new route registered in the api-server plugin. All JSON output uses the existing `jsonSuccess`/`jsonError` helpers from `cli/output.ts`.
|
||||
|
||||
**Tech Stack:** TypeScript, Node.js, Vitest, Fastify, ESM (`.js` extensions required on all imports)
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
**New files:**
|
||||
- `src/cli/commands/instances.ts` — `instances list` and `instances create` subcommands
|
||||
- `src/plugins/api-server/routes/workspace.ts` — `GET /api/v1/workspace` route
|
||||
- `src/core/__tests__/instances-cli.test.ts` — tests for instances list/create logic
|
||||
- `src/plugins/api-server/__tests__/auth-exchange.test.ts` — tests for POST /exchange
|
||||
- `src/plugins/api-server/__tests__/workspace-route.test.ts` — tests for GET /workspace
|
||||
|
||||
**Modified files:**
|
||||
- `src/cli/commands/index.ts` — export `cmdInstances`
|
||||
- `src/cli.ts` — register `instances` in `noInstanceCommands` map (does not require an existing instance root)
|
||||
- `src/cli/commands/start.ts` — extend `--json` output with `name`, `directory`, `port`
|
||||
- `src/cli/commands/default.ts` — extend `--json` output after onboarding wizard
|
||||
- `src/plugins/api-server/routes/auth.ts` — add `POST /exchange` route
|
||||
- `src/plugins/api-server/index.ts` (the plugin setup file) — register workspace route
|
||||
|
||||
---
|
||||
|
||||
## Task 1: `instances list` Command
|
||||
|
||||
**Files:**
|
||||
- Create: `src/cli/commands/instances.ts`
|
||||
- Create: `src/core/__tests__/instances-cli.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// src/core/__tests__/instances-cli.test.ts
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import path from 'node:path'
|
||||
|
||||
// We test the pure data-mapping logic extracted from the command
|
||||
// by mocking readInstanceInfo and InstanceRegistry
|
||||
|
||||
vi.mock('../../cli/commands/status.js', () => ({
|
||||
readInstanceInfo: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../core/instance/instance-registry.js', () => ({
|
||||
InstanceRegistry: vi.fn().mockImplementation(() => ({
|
||||
load: vi.fn(),
|
||||
list: vi.fn().mockReturnValue([]),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../core/instance/instance-context.js', () => ({
|
||||
getGlobalRoot: vi.fn().mockReturnValue('/Users/user/.openacp'),
|
||||
}))
|
||||
|
||||
import { buildInstanceListEntries } from '../../cli/commands/instances.js'
|
||||
import { readInstanceInfo } from '../../cli/commands/status.js'
|
||||
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
|
||||
|
||||
describe('buildInstanceListEntries', () => {
|
||||
beforeEach(() => { vi.clearAllMocks() })
|
||||
|
||||
it('returns empty array when no instances registered', async () => {
|
||||
const mockRegistry = { load: vi.fn(), list: vi.fn().mockReturnValue([]) }
|
||||
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
|
||||
const result = await buildInstanceListEntries()
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('maps registry entries to InstanceListEntry with correct fields', async () => {
|
||||
const mockRegistry = {
|
||||
load: vi.fn(),
|
||||
list: vi.fn().mockReturnValue([
|
||||
{ id: 'main', root: '/Users/user/.openacp' },
|
||||
]),
|
||||
}
|
||||
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
|
||||
vi.mocked(readInstanceInfo).mockReturnValue({
|
||||
name: 'Main', pid: 1234, apiPort: 21420,
|
||||
tunnelPort: null, runMode: 'daemon', channels: [],
|
||||
})
|
||||
|
||||
const result = await buildInstanceListEntries()
|
||||
expect(result).toEqual([{
|
||||
id: 'main',
|
||||
name: 'Main',
|
||||
directory: '/Users/user',
|
||||
root: '/Users/user/.openacp',
|
||||
status: 'running',
|
||||
port: 21420,
|
||||
}])
|
||||
})
|
||||
|
||||
it('sets status stopped when pid is null', async () => {
|
||||
const mockRegistry = {
|
||||
load: vi.fn(),
|
||||
list: vi.fn().mockReturnValue([{ id: 'dev', root: '/project/.openacp' }]),
|
||||
}
|
||||
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
|
||||
vi.mocked(readInstanceInfo).mockReturnValue({
|
||||
name: 'Dev', pid: null, apiPort: null,
|
||||
tunnelPort: null, runMode: null, channels: [],
|
||||
})
|
||||
|
||||
const result = await buildInstanceListEntries()
|
||||
expect(result[0]!.status).toBe('stopped')
|
||||
expect(result[0]!.port).toBeNull()
|
||||
})
|
||||
|
||||
it('computes directory as path.dirname(root)', async () => {
|
||||
const mockRegistry = {
|
||||
load: vi.fn(),
|
||||
list: vi.fn().mockReturnValue([
|
||||
{ id: 'proj', root: '/Users/user/my-project/.openacp' },
|
||||
]),
|
||||
}
|
||||
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
|
||||
vi.mocked(readInstanceInfo).mockReturnValue({
|
||||
name: 'Proj', pid: null, apiPort: null,
|
||||
tunnelPort: null, runMode: null, channels: [],
|
||||
})
|
||||
|
||||
const result = await buildInstanceListEntries()
|
||||
expect(result[0]!.directory).toBe('/Users/user/my-project')
|
||||
expect(result[0]!.root).toBe('/Users/user/my-project/.openacp')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/code/openacp-workspace/OpenACP
|
||||
pnpm test src/core/__tests__/instances-cli.test.ts
|
||||
```
|
||||
Expected: FAIL — `buildInstanceListEntries` not found
|
||||
|
||||
- [ ] **Step 3: Implement `instances list`**
|
||||
|
||||
```typescript
|
||||
// src/cli/commands/instances.ts
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
|
||||
import { getGlobalRoot } from '../../core/instance/instance-context.js'
|
||||
import { readInstanceInfo } from './status.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
import { wantsHelp } from './helpers.js'
|
||||
|
||||
export interface InstanceListEntry {
|
||||
id: string
|
||||
name: string | null
|
||||
directory: string
|
||||
root: string
|
||||
status: 'running' | 'stopped'
|
||||
port: number | null
|
||||
}
|
||||
|
||||
export async function buildInstanceListEntries(): Promise<InstanceListEntry[]> {
|
||||
const registryPath = path.join(getGlobalRoot(), 'instances.json')
|
||||
const registry = new InstanceRegistry(registryPath)
|
||||
await registry.load()
|
||||
return registry.list().map(entry => {
|
||||
const info = readInstanceInfo(entry.root)
|
||||
return {
|
||||
id: entry.id,
|
||||
name: info.name,
|
||||
directory: path.dirname(entry.root),
|
||||
root: entry.root,
|
||||
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
|
||||
port: info.apiPort,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function cmdInstances(args: string[] = [], _instanceRoot?: string): Promise<void> {
|
||||
const sub = args[0]
|
||||
const subArgs = args.slice(1)
|
||||
|
||||
if (!sub || sub === 'list') return cmdInstancesList(subArgs)
|
||||
if (sub === 'create') return cmdInstancesCreate(subArgs)
|
||||
|
||||
if (wantsHelp(args)) {
|
||||
printInstancesHelp()
|
||||
return
|
||||
}
|
||||
|
||||
console.error(`Unknown subcommand: instances ${sub}`)
|
||||
printInstancesHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
function printInstancesHelp(): void {
|
||||
console.log(`
|
||||
\x1b[1mopenacp instances\x1b[0m — Manage OpenACP instances
|
||||
|
||||
\x1b[1mSubcommands:\x1b[0m
|
||||
list List all registered instances
|
||||
create Create or register an instance
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output as JSON
|
||||
`)
|
||||
}
|
||||
|
||||
async function cmdInstancesList(args: string[]): Promise<void> {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const entries = await buildInstanceListEntries()
|
||||
|
||||
if (json) {
|
||||
jsonSuccess(entries)
|
||||
return
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
console.log('No instances registered.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(' Status ID Name Directory')
|
||||
console.log(' ' + '─'.repeat(70))
|
||||
for (const e of entries) {
|
||||
const status = e.status === 'running' ? '● running' : '○ stopped'
|
||||
const port = e.port ? `:${e.port}` : '—'
|
||||
const dir = e.directory.replace(os.homedir(), '~')
|
||||
const name = (e.name ?? e.id).padEnd(16)
|
||||
console.log(` ${status.padEnd(10)} ${e.id.padEnd(16)} ${name} ${dir} ${port}`)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
```bash
|
||||
pnpm test src/core/__tests__/instances-cli.test.ts
|
||||
```
|
||||
Expected: PASS (all 4 tests)
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/cli/commands/instances.ts src/core/__tests__/instances-cli.test.ts
|
||||
git commit -m "feat: add instances list command with --json output"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: `instances create` Command
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cli/commands/instances.ts`
|
||||
- Modify: `src/core/__tests__/instances-cli.test.ts`
|
||||
|
||||
- [ ] **Step 1: Add tests for create**
|
||||
|
||||
Add to `src/core/__tests__/instances-cli.test.ts`:
|
||||
|
||||
```typescript
|
||||
import fs from 'node:fs'
|
||||
import { cmdInstancesCreate } from '../../cli/commands/instances.js'
|
||||
|
||||
vi.mock('node:fs')
|
||||
vi.mock('../../core/config/config.js', () => ({
|
||||
ConfigManager: vi.fn().mockImplementation(() => ({
|
||||
exists: vi.fn().mockResolvedValue(false),
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('cmdInstancesCreate', () => {
|
||||
beforeEach(() => { vi.clearAllMocks() })
|
||||
|
||||
it('errors when --dir is missing', async () => {
|
||||
const mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
|
||||
const mockError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
await expect(cmdInstancesCreate([])).rejects.toThrow('exit')
|
||||
expect(mockError).toHaveBeenCalledWith(expect.stringContaining('--dir'))
|
||||
mockExit.mockRestore()
|
||||
mockError.mockRestore()
|
||||
})
|
||||
|
||||
it('errors when .openacp already exists and is registered', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true)
|
||||
const mockRegistry = {
|
||||
load: vi.fn(),
|
||||
getByRoot: vi.fn().mockReturnValue({ id: 'existing', root: '/path/.openacp' }),
|
||||
}
|
||||
vi.mocked(InstanceRegistry).mockImplementation(() => mockRegistry as any)
|
||||
|
||||
const mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
|
||||
const mockError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
await expect(cmdInstancesCreate(['--dir', '/path'])).rejects.toThrow('exit')
|
||||
expect(mockError).toHaveBeenCalledWith(expect.stringContaining('existing'))
|
||||
mockExit.mockRestore()
|
||||
mockError.mockRestore()
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
```bash
|
||||
pnpm test src/core/__tests__/instances-cli.test.ts
|
||||
```
|
||||
Expected: FAIL — `cmdInstancesCreate` not exported
|
||||
|
||||
- [ ] **Step 3: Implement `cmdInstancesCreate`**
|
||||
|
||||
Add to `src/cli/commands/instances.ts`:
|
||||
|
||||
```typescript
|
||||
import { generateSlug } from '../../core/instance/instance-context.js'
|
||||
|
||||
export async function cmdInstancesCreate(args: string[]): Promise<void> {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
// Parse flags
|
||||
const dirIdx = args.indexOf('--dir')
|
||||
const rawDir = dirIdx !== -1 ? args[dirIdx + 1] : undefined
|
||||
if (!rawDir) {
|
||||
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, '--dir is required')
|
||||
console.error('Error: --dir is required')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const fromIdx = args.indexOf('--from')
|
||||
const rawFrom = fromIdx !== -1 ? args[fromIdx + 1] : undefined
|
||||
const nameIdx = args.indexOf('--name')
|
||||
const instanceName = nameIdx !== -1 ? args[nameIdx + 1] : undefined
|
||||
const agentIdx = args.indexOf('--agent')
|
||||
const agent = agentIdx !== -1 ? args[agentIdx + 1] : undefined
|
||||
const noInteractive = args.includes('--no-interactive')
|
||||
|
||||
// Resolve absolute paths
|
||||
const resolvedDir = path.resolve(rawDir!.replace(/^~/, os.homedir()))
|
||||
const instanceRoot = path.join(resolvedDir, '.openacp')
|
||||
|
||||
const registryPath = path.join(getGlobalRoot(), 'instances.json')
|
||||
const registry = new InstanceRegistry(registryPath)
|
||||
await registry.load()
|
||||
|
||||
// Case: .openacp already exists
|
||||
if (fs.existsSync(instanceRoot)) {
|
||||
const existing = registry.getByRoot(instanceRoot)
|
||||
if (existing) {
|
||||
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, `Instance already exists at ${resolvedDir} (id: ${existing.id})`)
|
||||
console.error(`Error: Instance already exists at ${resolvedDir} (id: ${existing.id})`)
|
||||
process.exit(1)
|
||||
}
|
||||
// .openacp exists but not registered — register it
|
||||
const config = JSON.parse(fs.readFileSync(path.join(instanceRoot, 'config.json'), 'utf-8'))
|
||||
const name = config.instanceName ?? path.basename(resolvedDir)
|
||||
const baseId = generateSlug(name)
|
||||
const id = registry.uniqueId(baseId)
|
||||
registry.register(id, instanceRoot)
|
||||
await registry.save()
|
||||
return outputInstance(json, { id, root: instanceRoot })
|
||||
}
|
||||
|
||||
// Case: create new
|
||||
const name = instanceName ?? `openacp-${registry.list().length + 1}`
|
||||
const baseId = generateSlug(name)
|
||||
const id = registry.uniqueId(baseId)
|
||||
fs.mkdirSync(instanceRoot, { recursive: true })
|
||||
|
||||
if (rawFrom) {
|
||||
// Clone from existing
|
||||
const fromRoot = path.join(path.resolve(rawFrom.replace(/^~/, os.homedir())), '.openacp')
|
||||
if (!fs.existsSync(path.join(fromRoot, 'config.json'))) {
|
||||
if (json) jsonError(ErrorCodes.VALIDATION_ERROR, `No OpenACP instance found at ${rawFrom}`)
|
||||
console.error(`Error: No OpenACP instance found at ${rawFrom}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const { cloneInstance } = await import('../../core/setup/clone.js')
|
||||
await cloneInstance(fromRoot, instanceRoot, { instanceName: name })
|
||||
} else if (noInteractive) {
|
||||
// Minimal config
|
||||
const config: Record<string, unknown> = { instanceName: name, runMode: 'daemon' }
|
||||
if (agent) config.defaultAgent = agent
|
||||
fs.writeFileSync(path.join(instanceRoot, 'config.json'), JSON.stringify(config, null, 2))
|
||||
fs.writeFileSync(path.join(instanceRoot, 'plugins.json'), JSON.stringify({ version: 1, installed: {} }, null, 2))
|
||||
} else {
|
||||
// Run setup wizard (interactive)
|
||||
const { runSetup } = await import('../../core/setup/wizard.js')
|
||||
await runSetup({ instanceRoot, instanceName: name })
|
||||
}
|
||||
|
||||
registry.register(id, instanceRoot)
|
||||
await registry.save()
|
||||
return outputInstance(json, { id, root: instanceRoot })
|
||||
}
|
||||
|
||||
async function outputInstance(json: boolean, { id, root }: { id: string; root: string }): Promise<void> {
|
||||
const info = readInstanceInfo(root)
|
||||
const entry: InstanceListEntry = {
|
||||
id,
|
||||
name: info.name,
|
||||
directory: path.dirname(root),
|
||||
root,
|
||||
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
|
||||
port: info.apiPort,
|
||||
}
|
||||
if (json) {
|
||||
jsonSuccess(entry)
|
||||
return
|
||||
}
|
||||
console.log(`Instance created: ${info.name ?? id} at ${path.dirname(root)}`)
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** `generateSlug` is exported from `instance-context.ts`. `cloneInstance` in `core/setup/clone.js` may be a different path — check the actual clone logic location in the multi-instance implementation before using this import.
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/core/__tests__/instances-cli.test.ts
|
||||
```
|
||||
Expected: PASS (all tests)
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/cli/commands/instances.ts src/core/__tests__/instances-cli.test.ts
|
||||
git commit -m "feat: add instances create command"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Register `instances` in CLI
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cli/commands/index.ts`
|
||||
- Modify: `src/cli.ts`
|
||||
|
||||
- [ ] **Step 1: Export from index.ts**
|
||||
|
||||
In `src/cli/commands/index.ts`, add:
|
||||
```typescript
|
||||
export { cmdInstances } from './instances.js'
|
||||
```
|
||||
Add it with the other command exports (alphabetical order near `cmdIntegrate` or `cmdInstall`).
|
||||
|
||||
- [ ] **Step 2: Register in cli.ts**
|
||||
|
||||
In `src/cli.ts`, add `cmdInstances` to the import from `./cli/commands/index.js`:
|
||||
```typescript
|
||||
import {
|
||||
// ... existing imports ...
|
||||
cmdInstances,
|
||||
} from './cli/commands/index.js'
|
||||
```
|
||||
|
||||
In the `noInstanceCommands` object (not `instanceCommands`), add:
|
||||
```typescript
|
||||
'instances': async () => cmdInstances(args),
|
||||
```
|
||||
|
||||
`instances` must be in `noInstanceCommands` because it does not require an existing instance root — it reads the global `~/.openacp/instances.json` registry directly. Adding it to `instanceCommands` would cause `resolveRoot()` to prompt the user to select an instance before listing, which breaks the command.
|
||||
|
||||
- [ ] **Step 3: Verify registration works**
|
||||
|
||||
```bash
|
||||
pnpm build && node dist/cli.js instances list
|
||||
```
|
||||
Expected: Either table output (if instances registered) or "No instances registered."
|
||||
|
||||
```bash
|
||||
node dist/cli.js instances list --json
|
||||
```
|
||||
Expected: `{ "success": true, "data": [...] }`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/cli/commands/index.ts src/cli.ts
|
||||
git commit -m "feat: register instances subcommand in CLI"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Extend `start --json` Output
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cli/commands/start.ts`
|
||||
- Modify: `src/cli/commands/default.ts`
|
||||
|
||||
- [ ] **Step 1: Extend start.ts**
|
||||
|
||||
In `src/cli/commands/start.ts`, find the `jsonSuccess` call:
|
||||
```typescript
|
||||
// Before (line ~50)
|
||||
if (json) jsonSuccess({ pid: result.pid, instanceId: path.basename(root), dir: root })
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```typescript
|
||||
if (json) {
|
||||
// Read instance name and real id from registry
|
||||
let name: string | null = null
|
||||
let instanceId: string = path.basename(root)
|
||||
try {
|
||||
const { ConfigManager } = await import('../../core/config/config.js')
|
||||
const cm = new ConfigManager(path.join(root, 'config.json'))
|
||||
await cm.load()
|
||||
name = cm.get().instanceName ?? null
|
||||
} catch {}
|
||||
try {
|
||||
const { getGlobalRoot } = await import('../../core/instance/instance-context.js')
|
||||
const { InstanceRegistry } = await import('../../core/instance/instance-registry.js')
|
||||
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
|
||||
await reg.load()
|
||||
const entry = reg.getByRoot(root)
|
||||
if (entry) instanceId = entry.id
|
||||
} catch {}
|
||||
// Read port (may not be written yet, that's ok)
|
||||
let port: number | null = null
|
||||
try {
|
||||
port = parseInt(fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()) || null
|
||||
} catch {}
|
||||
jsonSuccess({
|
||||
pid: result.pid,
|
||||
instanceId,
|
||||
name,
|
||||
directory: path.dirname(root),
|
||||
dir: root, // keep for backward compat
|
||||
port,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Add `import fs from 'node:fs'` if not already present.
|
||||
|
||||
- [ ] **Step 2: Find equivalent output in default.ts**
|
||||
|
||||
In `src/cli/commands/default.ts`, search for any `jsonSuccess` call that outputs `pid`/`instanceId`. Apply the same extended fields. If the default command starts the server inline (not via `cmdStart`), locate the exact jsonSuccess call and extend it identically.
|
||||
|
||||
- [ ] **Step 3: Verify extended output**
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
# Start a test instance and check output:
|
||||
node dist/cli.js start --json 2>/dev/null | node -e "const d=require('fs').readFileSync('/dev/stdin','utf-8'); const j=JSON.parse(d.trim()); console.log(Object.keys(j.data))"
|
||||
```
|
||||
Expected output includes: `pid`, `instanceId`, `name`, `directory`, `dir`, `port`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/cli/commands/start.ts src/cli/commands/default.ts
|
||||
git commit -m "feat: extend start --json output with name, directory, port"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: `POST /api/v1/auth/exchange` Endpoint
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/auth.ts`
|
||||
- Modify: `src/plugins/api-server/auth/token-store.ts` (if `exchangeCode` not already implemented)
|
||||
- Create: `src/plugins/api-server/__tests__/auth-exchange.test.ts`
|
||||
|
||||
> **Check first (two things):**
|
||||
> 1. Open `src/plugins/api-server/index.ts`. There is likely already a `registerPlugin` call for `POST /exchange` registered with `{ auth: false }` — if so, the route registration boilerplate is done. Verify it calls `tokenStore.exchangeCode()`.
|
||||
> 2. Open `src/plugins/api-server/auth/token-store.ts` to confirm whether `exchangeCode()` is already defined. If `createCode()` is there but `exchangeCode()` is not, add it in this task. If both exist, skip Step 3 below.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// src/plugins/api-server/__tests__/auth-exchange.test.ts
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import Fastify from 'fastify'
|
||||
import { authRoutes } from '../routes/auth.js'
|
||||
|
||||
function makeTokenStore() {
|
||||
const codes = new Map<string, { tokenParams: any; expiresAt: string; used: boolean }>()
|
||||
return {
|
||||
createCode: vi.fn((params: any) => {
|
||||
const code = 'test-code-123'
|
||||
codes.set(code, {
|
||||
tokenParams: params,
|
||||
expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
|
||||
used: false,
|
||||
})
|
||||
return { code, expiresAt: codes.get(code)!.expiresAt }
|
||||
}),
|
||||
exchangeCode: vi.fn((code: string) => {
|
||||
const entry = codes.get(code)
|
||||
if (!entry) throw new Error('Invalid code')
|
||||
if (new Date(entry.expiresAt) < new Date()) throw new Error('Code expired')
|
||||
if (entry.used) throw new Error('Code already used')
|
||||
entry.used = true
|
||||
return entry.tokenParams
|
||||
}),
|
||||
create: vi.fn((params: any) => ({
|
||||
id: 'tok_test',
|
||||
name: params.name,
|
||||
role: params.role,
|
||||
scopes: params.scopes,
|
||||
createdAt: new Date().toISOString(),
|
||||
refreshDeadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
revoked: false,
|
||||
})),
|
||||
get: vi.fn(),
|
||||
revoke: vi.fn(),
|
||||
list: vi.fn().mockReturnValue([]),
|
||||
listCodes: vi.fn().mockReturnValue([]),
|
||||
revokeCode: vi.fn(),
|
||||
updateLastUsed: vi.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
async function buildApp(tokenStore: ReturnType<typeof makeTokenStore>) {
|
||||
const app = Fastify()
|
||||
app.decorateRequest('auth', null, [])
|
||||
app.addHook('onRequest', async (req) => {
|
||||
(req as any).auth = { type: 'secret', role: 'admin', scopes: ['*'] }
|
||||
})
|
||||
await app.register(authRoutes, { tokenStore, getJwtSecret: () => 'test-secret' })
|
||||
await app.ready()
|
||||
return app
|
||||
}
|
||||
|
||||
describe('POST /exchange', () => {
|
||||
let tokenStore: ReturnType<typeof makeTokenStore>
|
||||
let app: Awaited<ReturnType<typeof buildApp>>
|
||||
|
||||
beforeEach(async () => {
|
||||
tokenStore = makeTokenStore()
|
||||
app = await buildApp(tokenStore)
|
||||
})
|
||||
|
||||
it('returns JWT on valid code', async () => {
|
||||
// First create a code
|
||||
tokenStore.createCode({ role: 'admin', name: 'test', expire: '24h' })
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/exchange',
|
||||
payload: { code: 'test-code-123' },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body).toHaveProperty('accessToken')
|
||||
expect(body).toHaveProperty('tokenId')
|
||||
expect(body).toHaveProperty('expiresAt')
|
||||
expect(body).toHaveProperty('refreshDeadline')
|
||||
})
|
||||
|
||||
it('returns 401 for invalid code', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/exchange',
|
||||
payload: { code: 'nonexistent' },
|
||||
})
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 401 for already-used code', async () => {
|
||||
tokenStore.createCode({ role: 'admin', name: 'test', expire: '24h' })
|
||||
tokenStore.exchangeCode('test-code-123') // use it once
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/exchange',
|
||||
payload: { code: 'test-code-123' },
|
||||
})
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/auth-exchange.test.ts
|
||||
```
|
||||
Expected: FAIL — `POST /exchange` not found (404)
|
||||
|
||||
- [ ] **Step 3: Add `exchangeCode` to token store**
|
||||
|
||||
Open `src/plugins/api-server/auth/token-store.ts`. Check existing `createCode` implementation. Add `exchangeCode`:
|
||||
|
||||
```typescript
|
||||
// In TokenStore class, add after createCode():
|
||||
exchangeCode(code: string): CreateTokenOpts {
|
||||
const entry = this.codes.get(code)
|
||||
if (!entry) throw new Error('Invalid code')
|
||||
if (new Date(entry.expiresAt) < new Date()) {
|
||||
this.codes.delete(code)
|
||||
throw new Error('Code expired')
|
||||
}
|
||||
if (entry.used) throw new Error('Code already used')
|
||||
entry.used = true
|
||||
return entry.tokenParams
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** The `codes` map and its entry type may already be defined. Adapt to match the actual type. If `TokenStore` is an interface rather than a class, add `exchangeCode` to both the interface and the implementation.
|
||||
|
||||
- [ ] **Step 4: Add `POST /exchange` route to auth.ts (if not already present in index.ts)**
|
||||
|
||||
If the skeleton route in `index.ts` is incomplete, or auth.ts is the right place for the route body, add the implementation:
|
||||
|
||||
```typescript
|
||||
// POST /exchange — exchange one-time code for JWT (no auth required)
|
||||
// This route must be registered at the plugin level with { auth: false }
|
||||
// (via the third argument to registerPlugin in index.ts) — NOT via route-level config.
|
||||
app.post('/exchange', async (request, reply) => {
|
||||
const body = z.object({ code: z.string() }).parse(request.body)
|
||||
let tokenParams: any
|
||||
try {
|
||||
tokenParams = tokenStore.exchangeCode(body.code)
|
||||
} catch (err: any) {
|
||||
throw new AuthError('UNAUTHORIZED', err.message ?? 'Invalid code')
|
||||
}
|
||||
// Generate JWT using exchanged token params (same as POST /tokens)
|
||||
const stored = tokenStore.create(tokenParams)
|
||||
const durationMs = parseDuration(tokenParams.expire)
|
||||
const rfd = new Date(stored.refreshDeadline).getTime() / 1000
|
||||
const accessToken = signToken(
|
||||
{ sub: stored.id, role: stored.role, scopes: stored.scopes, rfd },
|
||||
getJwtSecret(),
|
||||
tokenParams.expire,
|
||||
)
|
||||
const expiresAt = new Date(Date.now() + durationMs).toISOString()
|
||||
return reply.send({
|
||||
accessToken,
|
||||
tokenId: stored.id,
|
||||
expiresAt,
|
||||
refreshDeadline: stored.refreshDeadline,
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Add `import { z } from 'zod'` at the top if not already present.
|
||||
|
||||
> **Auth bypass pattern:** The auth preHandler checks route/plugin registration options, not `request.routeOptions.config`. The correct way to mark a route group as unauthenticated is to pass `{ auth: false }` as the **third argument** to `registerPlugin(prefix, handler, { auth: false })` in `index.ts`. Do NOT use `{ config: { skipAuth: true } }` on individual route definitions — look at how the health or public routes bypass auth to confirm the exact call pattern used in this codebase.
|
||||
|
||||
- [ ] **Step 5: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/auth-exchange.test.ts
|
||||
```
|
||||
Expected: PASS (all 3 tests)
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/auth.ts src/plugins/api-server/auth/token-store.ts src/plugins/api-server/__tests__/auth-exchange.test.ts
|
||||
git commit -m "feat: add POST /auth/exchange for one-time code to JWT"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: `GET /api/v1/workspace` Endpoint
|
||||
|
||||
**Files:**
|
||||
- Create: `src/plugins/api-server/routes/workspace.ts`
|
||||
- Create: `src/plugins/api-server/__tests__/workspace-route.test.ts`
|
||||
- Modify: `src/plugins/api-server/index.ts` (the plugin setup file — check exact filename)
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// src/plugins/api-server/__tests__/workspace-route.test.ts
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import Fastify from 'fastify'
|
||||
import { workspaceRoute } from '../routes/workspace.js'
|
||||
|
||||
async function buildApp(opts: { id: string; name: string; directory: string; version: string }) {
|
||||
const app = Fastify()
|
||||
app.decorateRequest('auth', null, [])
|
||||
app.addHook('onRequest', async (req) => {
|
||||
(req as any).auth = { type: 'jwt', role: 'admin', scopes: ['system:health'] }
|
||||
})
|
||||
await app.register(workspaceRoute, opts)
|
||||
await app.ready()
|
||||
return app
|
||||
}
|
||||
|
||||
describe('GET /workspace', () => {
|
||||
it('returns workspace identity info', async () => {
|
||||
const app = await buildApp({
|
||||
id: 'main',
|
||||
name: 'Main',
|
||||
directory: '/Users/user',
|
||||
version: '2026.401.1',
|
||||
})
|
||||
const res = await app.inject({ method: 'GET', url: '/workspace' })
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body).toEqual({
|
||||
id: 'main',
|
||||
name: 'Main',
|
||||
directory: '/Users/user',
|
||||
version: '2026.401.1',
|
||||
})
|
||||
})
|
||||
|
||||
it('requires authentication', async () => {
|
||||
const app = Fastify()
|
||||
app.decorateRequest('auth', null, [])
|
||||
app.addHook('onRequest', async (req) => {
|
||||
// No auth set — simulate unauthenticated request
|
||||
(req as any).auth = null
|
||||
})
|
||||
await app.register(workspaceRoute, {
|
||||
id: 'main', name: 'Main', directory: '/Users/user', version: '1.0',
|
||||
})
|
||||
await app.ready()
|
||||
// Route should exist and return data when auth is present
|
||||
// Authentication enforcement is handled by the preHandler in the plugin setup, not the route itself
|
||||
const res = await app.inject({ method: 'GET', url: '/workspace' })
|
||||
// With no auth preHandler in this test, it returns 200 (auth is enforced at plugin level)
|
||||
expect(res.statusCode).toBe(200)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/workspace-route.test.ts
|
||||
```
|
||||
Expected: FAIL — module not found
|
||||
|
||||
- [ ] **Step 3: Implement workspace route**
|
||||
|
||||
```typescript
|
||||
// src/plugins/api-server/routes/workspace.ts
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import path from 'node:path'
|
||||
|
||||
export interface WorkspaceRouteOpts {
|
||||
id: string
|
||||
name: string
|
||||
directory: string
|
||||
version: string
|
||||
}
|
||||
|
||||
export async function workspaceRoute(
|
||||
app: FastifyInstance,
|
||||
opts: WorkspaceRouteOpts,
|
||||
): Promise<void> {
|
||||
app.get('/workspace', async () => ({
|
||||
id: opts.id,
|
||||
name: opts.name,
|
||||
directory: opts.directory,
|
||||
version: opts.version,
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Register in api-server plugin setup**
|
||||
|
||||
Find the api-server plugin setup file (likely `src/plugins/api-server/index.ts`). Locate where other routes are registered (e.g., where `authRoutes` is registered). Add:
|
||||
|
||||
```typescript
|
||||
import { workspaceRoute } from './routes/workspace.js'
|
||||
import path from 'node:path'
|
||||
|
||||
// In the setup function, after other route registrations:
|
||||
const instanceRoot = ctx.paths.root // or however the plugin accesses instanceRoot
|
||||
const version = /* get from package.json or config */ '0.0.0'
|
||||
let workspaceId = 'main'
|
||||
let workspaceName = 'Main'
|
||||
let workspaceDir = path.dirname(instanceRoot)
|
||||
try {
|
||||
const { InstanceRegistry } = await import('../../core/instance/instance-registry.js')
|
||||
const { getGlobalRoot } = await import('../../core/instance/instance-context.js')
|
||||
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
|
||||
await reg.load()
|
||||
const entry = reg.getByRoot(instanceRoot)
|
||||
if (entry) workspaceId = entry.id
|
||||
} catch {}
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(path.join(instanceRoot, 'config.json'), 'utf-8'))
|
||||
workspaceName = config.instanceName ?? workspaceName
|
||||
} catch {}
|
||||
|
||||
apiServer.registerPlugin('/api/v1', async (pluginApp) => {
|
||||
await pluginApp.register(workspaceRoute, {
|
||||
id: workspaceId,
|
||||
name: workspaceName,
|
||||
directory: workspaceDir,
|
||||
version,
|
||||
})
|
||||
}, { auth: true })
|
||||
```
|
||||
|
||||
> **Note:** The exact way `instanceRoot` and config are accessed in the plugin context may differ. Look at how other routes in the same file access instance data and follow the same pattern. The `version` should come from `package.json` — look for how other parts of the codebase read it.
|
||||
|
||||
- [ ] **Step 5: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/workspace-route.test.ts
|
||||
```
|
||||
Expected: PASS
|
||||
|
||||
```bash
|
||||
pnpm build && pnpm test
|
||||
```
|
||||
Expected: All tests pass, no TypeScript errors
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/workspace.ts src/plugins/api-server/__tests__/workspace-route.test.ts src/plugins/api-server/index.ts
|
||||
git commit -m "feat: add GET /api/v1/workspace endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review Checklist
|
||||
|
||||
After all tasks are complete:
|
||||
|
||||
- [ ] `openacp instances list --json` outputs correct schema (`id`, `name`, `directory`, `root`, `status`, `port`)
|
||||
- [ ] `openacp instances create --dir /path --no-interactive --json` creates instance and returns JSON
|
||||
- [ ] `openacp instances create --dir /path --from /existing --json` clones and returns JSON
|
||||
- [ ] `openacp start --json` output includes `name`, `directory`, `port` in addition to existing fields
|
||||
- [ ] `POST /api/v1/auth/exchange` returns JWT on valid code, 401 on invalid/expired/used
|
||||
- [ ] `GET /api/v1/workspace` returns `{id, name, directory, version}` with authentication
|
||||
- [ ] `pnpm test` passes with no failures
|
||||
- [ ] `pnpm build` compiles with no TypeScript errors
|
||||
604
docs/superpowers/plans/2026-04-02-menu-button-fix.md
Normal file
604
docs/superpowers/plans/2026-04-02-menu-button-fix.md
Normal file
@ -0,0 +1,604 @@
|
||||
# Menu Button & Command Dispatch Fix — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Fix all broken/degraded menu buttons and slash commands so they use Telegram-specific rich UI handlers instead of generic core handlers.
|
||||
|
||||
**Architecture:** Add an intercept map (`TELEGRAM_OVERRIDES`) that routes 6 commands to Telegram-specific handlers before they reach `CommandRegistry`. Fix the `m:` handler's `callback` case to dispatch Settings and New Session. Add a button-driven New Session flow (`ns:` prefix) that only delegates to AI for custom workspace input.
|
||||
|
||||
**Tech Stack:** TypeScript, grammY (Telegram Bot Framework), Vitest
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-04-02-menu-button-fix-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| File | Responsibility | Change type |
|
||||
|------|---------------|-------------|
|
||||
| `src/plugins/telegram/commands/index.ts` | Callback routing hub — broad `m:` handler, exports | Modify |
|
||||
| `src/plugins/telegram/commands/telegram-overrides.ts` | Intercept map: command name → Telegram handler | Create |
|
||||
| `src/plugins/telegram/commands/new-session.ts` | New Session button flow (`ns:` prefix callbacks) | Modify |
|
||||
| `src/plugins/telegram/commands/session.ts` | Add `m:topics` callback handler | Modify |
|
||||
| `src/plugins/telegram/adapter.ts` | Intercept slash commands before `registry.execute()` | Modify |
|
||||
| `src/core/menu/core-items.ts` | Change New Session action type | Modify |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Create Telegram Overrides Map
|
||||
|
||||
**Files:**
|
||||
- Create: `src/plugins/telegram/commands/telegram-overrides.ts`
|
||||
|
||||
This is a simple lookup table. No dependencies on adapter.ts — avoids circular imports.
|
||||
|
||||
- [ ] **Step 1: Create the intercept map file**
|
||||
|
||||
```typescript
|
||||
// src/plugins/telegram/commands/telegram-overrides.ts
|
||||
import type { Context } from 'grammy'
|
||||
import type { OpenACPCore } from '../../../core/index.js'
|
||||
import { handleAgents } from './agents.js'
|
||||
import { handleTopics } from './session.js'
|
||||
import { handleDoctor } from './doctor.js'
|
||||
import { handleUpdate, handleRestart } from './admin.js'
|
||||
import { handleHelp } from './menu.js'
|
||||
|
||||
/**
|
||||
* Commands that should be intercepted and handled by Telegram-specific
|
||||
* handlers instead of going through CommandRegistry core handlers.
|
||||
*
|
||||
* These handlers use grammY Context for rich UI (inline keyboards,
|
||||
* message editing, pagination) that CommandResponse cannot express.
|
||||
*/
|
||||
export const TELEGRAM_OVERRIDES: Record<
|
||||
string,
|
||||
(ctx: Context, core: OpenACPCore) => Promise<void>
|
||||
> = {
|
||||
agents: (ctx, core) => handleAgents(ctx, core),
|
||||
sessions: (ctx, core) => handleTopics(ctx, core),
|
||||
doctor: (ctx) => handleDoctor(ctx),
|
||||
update: (ctx, core) => handleUpdate(ctx, core),
|
||||
restart: (ctx, core) => handleRestart(ctx, core),
|
||||
help: (ctx) => handleHelp(ctx),
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/telegram-overrides.ts
|
||||
git commit -m "feat: add Telegram command intercept map"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Intercept Slash Commands in Adapter
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/adapter.ts` (lines 322-394, the `bot.on("message:text")` handler)
|
||||
|
||||
Insert the intercept check after extracting `commandName` (line 344) but before `registry.execute()` (line 360).
|
||||
|
||||
- [ ] **Step 1: Add import at top of adapter.ts**
|
||||
|
||||
Add after the existing imports from `./commands/index.js`:
|
||||
|
||||
```typescript
|
||||
import { TELEGRAM_OVERRIDES } from './commands/telegram-overrides.js'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add intercept check in the slash command handler**
|
||||
|
||||
In the `bot.on("message:text")` handler, after line 346 (`if (!def) return next();`), add:
|
||||
|
||||
```typescript
|
||||
// Telegram-specific override — use rich handler instead of core CommandRegistry
|
||||
const telegramOverride = TELEGRAM_OVERRIDES[commandName]
|
||||
if (telegramOverride) {
|
||||
try {
|
||||
await telegramOverride(ctx, this.core as OpenACPCore)
|
||||
} catch (err) {
|
||||
await ctx.reply(`⚠️ Command failed: ${String(err)}`)
|
||||
}
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
This goes between line 346 (`if (!def) return next()`) and line 348 (`const chatId = ctx.chat.id`).
|
||||
|
||||
- [ ] **Step 3: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/adapter.ts src/plugins/telegram/commands/telegram-overrides.ts
|
||||
git commit -m "feat: intercept slash commands for Telegram-specific handlers
|
||||
|
||||
/agents, /sessions, /doctor, /update, /restart, /help now use
|
||||
rich Telegram handlers with inline keyboards instead of generic
|
||||
CommandRegistry core responses."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Fix `m:` Handler — Command Type Intercept
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/commands/index.ts` (the broad `m:` handler, lines 67-134)
|
||||
|
||||
The `command` case currently dispatches everything through `CommandRegistry`. Add intercept check.
|
||||
|
||||
- [ ] **Step 1: Add import for TELEGRAM_OVERRIDES**
|
||||
|
||||
Add at top of `index.ts`:
|
||||
|
||||
```typescript
|
||||
import { TELEGRAM_OVERRIDES } from './telegram-overrides.js'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace the `command` case in the broad `m:` handler**
|
||||
|
||||
Replace lines 82-114 (the entire `case 'command': { ... break }` block):
|
||||
|
||||
```typescript
|
||||
case 'command': {
|
||||
// Check Telegram-specific override first
|
||||
const cmdName = item.action.command.replace(/^\//, '').split(' ')[0]
|
||||
const telegramOverride = TELEGRAM_OVERRIDES[cmdName]
|
||||
if (telegramOverride) {
|
||||
try {
|
||||
await telegramOverride(ctx, core)
|
||||
} catch (err) {
|
||||
await ctx.reply(`⚠️ Command failed: ${String(err)}`).catch(() => {})
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// Fallback: dispatch through CommandRegistry for commands without overrides
|
||||
if (!registry) return
|
||||
const response = await registry.execute(item.action.command, {
|
||||
raw: '',
|
||||
channelId: 'telegram',
|
||||
userId: String(ctx.from.id),
|
||||
sessionId: null,
|
||||
reply: async () => {},
|
||||
})
|
||||
if (response.type !== 'delegated' && response.type !== 'silent') {
|
||||
if (response.type === 'text') {
|
||||
await ctx.reply(response.text, { parse_mode: 'HTML' }).catch(() => {})
|
||||
} else if (response.type === 'error') {
|
||||
await ctx.reply(`⚠️ ${response.message}`).catch(() => {})
|
||||
} else if (response.type === 'list') {
|
||||
const lines = response.items.map((i: { label: string; detail?: string }) => `• ${i.label}${i.detail ? ` — ${i.detail}` : ''}`).join('\n')
|
||||
await ctx.reply(`${response.title}\n${lines}`, { parse_mode: 'HTML' }).catch(() => {})
|
||||
} else if (response.type === 'menu') {
|
||||
const { InlineKeyboard } = await import('grammy')
|
||||
const kb = new InlineKeyboard()
|
||||
for (const opt of response.options) {
|
||||
kb.text(opt.label, `c/${opt.command}`).row()
|
||||
}
|
||||
await ctx.reply(response.title, { parse_mode: 'HTML', reply_markup: kb }).catch(() => {})
|
||||
} else if (response.type === 'confirm') {
|
||||
const { InlineKeyboard } = await import('grammy')
|
||||
const kb = new InlineKeyboard()
|
||||
.text('✅ Yes', `c/${response.onYes}`)
|
||||
.text('❌ No', `c/${response.onNo}`)
|
||||
await ctx.reply(response.question, { reply_markup: kb }).catch(() => {})
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/index.ts
|
||||
git commit -m "feat: intercept menu button commands for Telegram handlers
|
||||
|
||||
Menu buttons for Agents, Sessions, Doctor, Update, Restart, Help
|
||||
now use rich Telegram handlers instead of generic core responses."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Fix `m:` Handler — Callback Type (Settings)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/commands/index.ts` (the `callback` case, line 130-132)
|
||||
|
||||
- [ ] **Step 1: Replace the `callback` case**
|
||||
|
||||
Replace lines 130-132:
|
||||
|
||||
```typescript
|
||||
case 'callback':
|
||||
// Pass through to specific callback handlers
|
||||
break
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```typescript
|
||||
case 'callback': {
|
||||
const cbData = item.action.callbackData
|
||||
if (cbData === 's:settings') {
|
||||
await handleSettings(ctx, core)
|
||||
}
|
||||
// ns: callbacks handled in Task 6 (New Session flow)
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/index.ts
|
||||
git commit -m "fix: Settings menu button now opens settings keyboard
|
||||
|
||||
The callback action type was silently doing nothing (break).
|
||||
Now dispatches s:settings to handleSettings directly."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Fix `m:topics` Refresh Button
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/commands/session.ts` (inside `setupSessionCallbacks`)
|
||||
|
||||
The Refresh button in the sessions list sends `m:topics` which reaches the broad `m:` handler → `menuRegistry.getItem("topics")` → undefined → nothing. Fix by adding a specific handler in `setupSessionCallbacks` which runs BEFORE the broad handler.
|
||||
|
||||
- [ ] **Step 1: Add `m:topics` callback handler in `setupSessionCallbacks`**
|
||||
|
||||
In `session.ts`, inside `setupSessionCallbacks()`, add after the existing `bot.callbackQuery(/^m:cleanup/, ...)` handler (after line 355):
|
||||
|
||||
```typescript
|
||||
// Refresh sessions list (button created by handleTopics)
|
||||
bot.callbackQuery('m:topics', async (ctx) => {
|
||||
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
|
||||
await handleTopics(ctx, core)
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/session.ts
|
||||
git commit -m "fix: Refresh button in sessions list now works
|
||||
|
||||
m:topics callback was falling through to broad m: handler which
|
||||
couldn't find a menu item for 'topics'. Now handled directly by
|
||||
setupSessionCallbacks before the broad handler."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: New Session Button Flow
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/commands/new-session.ts` — add `setupNewSessionCallbacks()` and `showAgentPicker()`
|
||||
- Modify: `src/plugins/telegram/commands/index.ts` — register `ns:` callbacks, update `callback` case
|
||||
- Modify: `src/core/menu/core-items.ts` — change New Session action type
|
||||
|
||||
### Step 1: Add New Session button flow to new-session.ts
|
||||
|
||||
- [ ] **Step 1a: Add the workspace cache and agent picker function**
|
||||
|
||||
Add at the bottom of `new-session.ts`, before the final export:
|
||||
|
||||
```typescript
|
||||
// --- New Session button flow (ns: prefix) ---
|
||||
|
||||
/** Workspace cache for callback data — avoids Telegram's 64-byte callback limit */
|
||||
const workspaceCache = new Map<number, { agentKey: string; workspace: string }>()
|
||||
let nextWsId = 0
|
||||
|
||||
export async function showAgentPicker(ctx: Context, core: OpenACPCore, chatId: number): Promise<void> {
|
||||
const catalog = core.agentCatalog
|
||||
const installed = catalog.getAvailable().filter((i) => i.installed)
|
||||
|
||||
if (installed.length === 0) {
|
||||
await ctx.reply('No agents installed. Use /install to add one.', { parse_mode: 'HTML' }).catch(() => {})
|
||||
return
|
||||
}
|
||||
|
||||
// Single agent → skip picker, go to workspace
|
||||
if (installed.length === 1) {
|
||||
await showWorkspacePicker(ctx, core, chatId, installed[0].key)
|
||||
return
|
||||
}
|
||||
|
||||
const kb = new InlineKeyboard()
|
||||
for (let i = 0; i < installed.length; i += 2) {
|
||||
const row = installed.slice(i, i + 2)
|
||||
for (const agent of row) {
|
||||
kb.text(agent.name, `ns:agent:${agent.key}`)
|
||||
}
|
||||
kb.row()
|
||||
}
|
||||
|
||||
await ctx.reply('<b>🆕 New Session</b>\nSelect an agent:', {
|
||||
parse_mode: 'HTML',
|
||||
reply_markup: kb,
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
async function showWorkspacePicker(ctx: Context, core: OpenACPCore, chatId: number, agentKey: string): Promise<void> {
|
||||
const records = core.sessionManager.listRecords()
|
||||
const recentWorkspaces = [...new Set(records.map((r: any) => r.workingDir).filter(Boolean))]
|
||||
.slice(0, 5)
|
||||
|
||||
const config = core.configManager.get()
|
||||
const baseDir = config.workspace.baseDir
|
||||
|
||||
// Ensure baseDir is always an option
|
||||
const workspaces = recentWorkspaces.includes(baseDir)
|
||||
? recentWorkspaces
|
||||
: [baseDir, ...recentWorkspaces].slice(0, 5)
|
||||
|
||||
const kb = new InlineKeyboard()
|
||||
for (const ws of workspaces) {
|
||||
const id = nextWsId++
|
||||
workspaceCache.set(id, { agentKey, workspace: ws })
|
||||
// Show shortened path for display
|
||||
const label = ws.startsWith('/Users/') ? '~/' + ws.split('/').slice(3).join('/') : ws
|
||||
kb.text(`📁 ${label}`, `ns:ws:${id}`).row()
|
||||
}
|
||||
// Custom path → delegate to AI
|
||||
const customId = nextWsId++
|
||||
workspaceCache.set(customId, { agentKey, workspace: '' }) // empty = custom
|
||||
kb.text('📁 Custom path...', `ns:custom:${agentKey}`).row()
|
||||
|
||||
const agentLabel = escapeHtml(agentKey)
|
||||
await ctx.reply(`<b>🆕 New Session</b>\nAgent: <code>${agentLabel}</code>\n\nSelect workspace:`, {
|
||||
parse_mode: 'HTML',
|
||||
reply_markup: kb,
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
export function setupNewSessionCallbacks(
|
||||
bot: Bot,
|
||||
core: OpenACPCore,
|
||||
chatId: number,
|
||||
getAssistantSession?: () => { topicId: number; enqueuePrompt: (p: string) => Promise<void> } | undefined,
|
||||
): void {
|
||||
// Agent picker (also triggered from m: handler callback case)
|
||||
bot.callbackQuery('ns:start', async (ctx) => {
|
||||
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
|
||||
await showAgentPicker(ctx, core, chatId)
|
||||
})
|
||||
|
||||
bot.callbackQuery(/^ns:agent:/, async (ctx) => {
|
||||
const agentKey = ctx.callbackQuery.data.replace('ns:agent:', '')
|
||||
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
|
||||
await showWorkspacePicker(ctx, core, chatId, agentKey)
|
||||
})
|
||||
|
||||
bot.callbackQuery(/^ns:ws:/, async (ctx) => {
|
||||
const id = parseInt(ctx.callbackQuery.data.replace('ns:ws:', ''), 10)
|
||||
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
|
||||
|
||||
const entry = workspaceCache.get(id)
|
||||
if (!entry) {
|
||||
await ctx.reply('⚠️ Session expired. Please try again via /menu.').catch(() => {})
|
||||
return
|
||||
}
|
||||
workspaceCache.delete(id)
|
||||
await createSessionDirect(ctx, core, chatId, entry.agentKey, entry.workspace)
|
||||
})
|
||||
|
||||
bot.callbackQuery(/^ns:custom:/, async (ctx) => {
|
||||
const agentKey = ctx.callbackQuery.data.replace('ns:custom:', '')
|
||||
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
|
||||
|
||||
const assistant = getAssistantSession?.()
|
||||
if (assistant) {
|
||||
await assistant.enqueuePrompt(
|
||||
`User wants to create a new session with agent "${agentKey}". Ask them for the workspace (project directory) path, then create the session.`
|
||||
)
|
||||
} else {
|
||||
await ctx.reply(
|
||||
`Usage: <code>/new ${escapeHtml(agentKey)} <workspace-path></code>`,
|
||||
{ parse_mode: 'HTML' },
|
||||
).catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 1b: Add `InlineKeyboard` to imports**
|
||||
|
||||
The top of `new-session.ts` has `import type { Bot, Context } from "grammy"` (line 1). Change it to:
|
||||
|
||||
```typescript
|
||||
import type { Bot, Context } from "grammy";
|
||||
import { InlineKeyboard } from "grammy";
|
||||
```
|
||||
|
||||
Remove the `import { InlineKeyboard } from 'grammy'` line from inside the new code block added in Step 1a (it's a top-level import now).
|
||||
|
||||
- [ ] **Step 1c: Export `showAgentPicker` and `setupNewSessionCallbacks` from the file**
|
||||
|
||||
Both are already exported via `export async function` and `export function` in the code above. No additional change needed.
|
||||
|
||||
### Step 2: Register ns: callbacks in index.ts
|
||||
|
||||
- [ ] **Step 2a: Add imports in index.ts**
|
||||
|
||||
Add to the imports from `./new-session.js`:
|
||||
|
||||
```typescript
|
||||
import { handleNew, handleNewChat, createSessionDirect, showAgentPicker, setupNewSessionCallbacks } from './new-session.js'
|
||||
```
|
||||
|
||||
(Replace the existing import line for `new-session.js`.)
|
||||
|
||||
- [ ] **Step 2b: Register ns: callbacks in setupAllCallbacks**
|
||||
|
||||
Add after the `na:` handler (line 62) and before the `ar:` handler (line 65):
|
||||
|
||||
```typescript
|
||||
// New Session button flow — must be before broad m: handler
|
||||
setupNewSessionCallbacks(bot, core, chatId, getAssistantSession);
|
||||
```
|
||||
|
||||
- [ ] **Step 2c: Update the `callback` case to handle ns:start**
|
||||
|
||||
Update the `callback` case (from Task 4) to also handle `ns:`:
|
||||
|
||||
```typescript
|
||||
case 'callback': {
|
||||
const cbData = item.action.callbackData
|
||||
if (cbData === 's:settings') {
|
||||
await handleSettings(ctx, core)
|
||||
} else if (cbData === 'ns:start') {
|
||||
await showAgentPicker(ctx, core, chatId)
|
||||
}
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Update core menu item
|
||||
|
||||
- [ ] **Step 3a: Change New Session action in core-items.ts**
|
||||
|
||||
In `src/core/menu/core-items.ts`, replace line 9:
|
||||
|
||||
```typescript
|
||||
action: { type: 'delegate', prompt: 'User wants new session. Guide them through agent and workspace selection.' },
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```typescript
|
||||
action: { type: 'callback', callbackData: 'ns:start' },
|
||||
```
|
||||
|
||||
### Step 4: Build and commit
|
||||
|
||||
- [ ] **Step 4a: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 4b: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/new-session.ts \
|
||||
src/plugins/telegram/commands/index.ts \
|
||||
src/core/menu/core-items.ts
|
||||
git commit -m "feat: button-driven New Session flow
|
||||
|
||||
New Session menu button now shows:
|
||||
1. Agent picker (inline buttons, skip if only 1 agent)
|
||||
2. Workspace picker (recent workspaces from session history)
|
||||
3. 'Custom path...' delegates to AI for text input
|
||||
4. Direct workspace selection creates session immediately
|
||||
|
||||
Uses workspace cache with numeric IDs to stay within
|
||||
Telegram's 64-byte callback data limit."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Add re-export for telegram-overrides
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/telegram/commands/index.ts`
|
||||
|
||||
- [ ] **Step 1: Add re-export**
|
||||
|
||||
Add to the re-exports section at the bottom of `index.ts`:
|
||||
|
||||
```typescript
|
||||
export { TELEGRAM_OVERRIDES } from './telegram-overrides.js'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify build passes**
|
||||
|
||||
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
|
||||
Expected: No errors
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/telegram/commands/index.ts
|
||||
git commit -m "chore: re-export TELEGRAM_OVERRIDES from commands index"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Manual Smoke Test
|
||||
|
||||
No automated tests for UI callback flows — these require grammY bot context which is hard to mock meaningfully. Verify manually.
|
||||
|
||||
- [ ] **Step 1: Build and start**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/openacp-workspace/OpenACP && pnpm build
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Test each menu button in Telegram**
|
||||
|
||||
Open the Telegram group, type `/menu`, then test each button:
|
||||
|
||||
| Button | Expected behavior | Pass? |
|
||||
|--------|-------------------|-------|
|
||||
| 🆕 New Session | Shows agent picker buttons (or workspace picker if 1 agent) | |
|
||||
| 📋 Sessions | Shows session list with status emoji + cleanup buttons + Refresh | |
|
||||
| 📊 Status | Shows status text | |
|
||||
| 🤖 Agents | Shows paginated agent list with install buttons | |
|
||||
| ⚙️ Settings | Shows settings keyboard with toggle/select options | |
|
||||
| 🔗 Integrate | Shows integration menu | |
|
||||
| 🔄 Restart | Sends restart message, then restarts | |
|
||||
| ⬆️ Update | Checks version, updates if available | |
|
||||
| ❓ Help | Shows rich formatted help | |
|
||||
| 🩺 Doctor | Runs diagnostics, shows report with fix buttons | |
|
||||
|
||||
- [ ] **Step 3: Test slash commands**
|
||||
|
||||
Type each command directly:
|
||||
|
||||
| Command | Expected | Pass? |
|
||||
|---------|----------|-------|
|
||||
| `/agents` | Paginated list with install buttons | |
|
||||
| `/sessions` | Session list with cleanup + refresh | |
|
||||
| `/doctor` | Diagnostic report with fix buttons | |
|
||||
| `/help` | Rich formatted help | |
|
||||
|
||||
- [ ] **Step 4: Test New Session full flow**
|
||||
|
||||
1. `/menu` → tap "🆕 New Session" → agent picker appears
|
||||
2. Tap an agent → workspace picker appears (recent workspaces + Custom)
|
||||
3. Tap a recent workspace → session created with topic
|
||||
4. Repeat: tap "Custom path..." → AI asks for workspace path
|
||||
|
||||
- [ ] **Step 5: Test Refresh button**
|
||||
|
||||
1. `/menu` → tap "📋 Sessions" → session list with Refresh button
|
||||
2. Tap "Refresh" → list refreshes
|
||||
1499
docs/superpowers/plans/2026-04-02-openacp-managed-tunnel.md
Normal file
1499
docs/superpowers/plans/2026-04-02-openacp-managed-tunnel.md
Normal file
File diff suppressed because it is too large
Load Diff
1487
docs/superpowers/plans/2026-04-03-multi-adapter-session-routing.md
Normal file
1487
docs/superpowers/plans/2026-04-03-multi-adapter-session-routing.md
Normal file
File diff suppressed because it is too large
Load Diff
966
docs/superpowers/plans/2026-04-03-plugins-api.md
Normal file
966
docs/superpowers/plans/2026-04-03-plugins-api.md
Normal file
@ -0,0 +1,966 @@
|
||||
# Plugins API Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add `/api/v1/plugins` route group to the api-server plugin, exposing list, marketplace, enable, disable, and uninstall endpoints backed by `LifecycleManager` and `PluginRegistry`.
|
||||
|
||||
**Architecture:** A new `plugins.ts` route file is registered in `api-server/index.ts`. It receives `lifecycleManager` via `RouteDeps`. Two getters are added to `LifecycleManager` to expose its private `loadOrder` array and `instanceRoot`. All endpoints require `system:admin` scope.
|
||||
|
||||
**Tech Stack:** Fastify, Vitest, TypeScript ESM (`.js` imports), `LifecycleManager`, `PluginRegistry`, `RegistryClient`, `importFromDir`.
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| Action | File | Responsibility |
|
||||
|--------|------|----------------|
|
||||
| Modify | `src/core/plugin/lifecycle-manager.ts` | Add `plugins` and `instanceRoot` public getters |
|
||||
| Modify | `src/plugins/api-server/routes/types.ts` | Add `lifecycleManager?: LifecycleManager` to `RouteDeps` |
|
||||
| Create | `src/plugins/api-server/routes/plugins.ts` | All 5 plugin endpoints |
|
||||
| Create | `src/plugins/api-server/__tests__/routes-plugins.test.ts` | Full route test suite |
|
||||
| Modify | `src/plugins/api-server/index.ts` | Import, wire, and register plugins route |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add public getters to LifecycleManager
|
||||
|
||||
`loadOrder` and `instanceRoot` are both private but needed by the route. Add getters without breaking the existing API.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/plugin/lifecycle-manager.ts`
|
||||
|
||||
- [ ] **Step 1: Rename private field and add getters**
|
||||
|
||||
In `src/core/plugin/lifecycle-manager.ts`, rename `private instanceRoot` to `private _instanceRoot`, then add two getters after the existing `get registry()` getter:
|
||||
|
||||
```ts
|
||||
// Change:
|
||||
private instanceRoot: string | undefined
|
||||
// To:
|
||||
private _instanceRoot: string | undefined
|
||||
```
|
||||
|
||||
Update all internal uses of `this.instanceRoot` to `this._instanceRoot` (constructor assignment and createPluginContext call):
|
||||
|
||||
```ts
|
||||
// constructor:
|
||||
this._instanceRoot = opts?.instanceRoot
|
||||
|
||||
// createPluginContext call:
|
||||
instanceRoot: this._instanceRoot,
|
||||
```
|
||||
|
||||
Add getters after `get registry()`:
|
||||
|
||||
```ts
|
||||
/** Plugin definitions currently in load order (loaded + failed). */
|
||||
get plugins(): OpenACPPlugin[] {
|
||||
return [...this.loadOrder]
|
||||
}
|
||||
|
||||
/** Root directory of this OpenACP instance (e.g. ~/.openacp). */
|
||||
get instanceRoot(): string | undefined {
|
||||
return this._instanceRoot
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run existing lifecycle tests to verify no regression**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/code/openacp-workspace/OpenACP
|
||||
pnpm test src/core/plugin/__tests__/lifecycle-manager.test.ts
|
||||
```
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/core/plugin/lifecycle-manager.ts
|
||||
git commit -m "feat(lifecycle): expose plugins and instanceRoot as public getters"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Extend RouteDeps
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/types.ts`
|
||||
|
||||
- [ ] **Step 1: Add import and field**
|
||||
|
||||
In `src/plugins/api-server/routes/types.ts`, add:
|
||||
|
||||
```ts
|
||||
import type { LifecycleManager } from '../../../core/plugin/lifecycle-manager.js'
|
||||
|
||||
export interface RouteDeps {
|
||||
core: OpenACPCore;
|
||||
topicManager?: TopicManager;
|
||||
startedAt: number;
|
||||
getVersion: () => string;
|
||||
commandRegistry?: CommandRegistry;
|
||||
authPreHandler?: preHandlerHookHandler;
|
||||
contextManager?: ContextManager;
|
||||
/** LifecycleManager for plugin state queries and hot-load operations. */
|
||||
lifecycleManager?: LifecycleManager;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify TypeScript compiles**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/code/openacp-workspace/OpenACP
|
||||
pnpm build 2>&1 | head -20
|
||||
```
|
||||
|
||||
Expected: no errors related to `RouteDeps`.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/types.ts
|
||||
git commit -m "feat(api-server): add lifecycleManager to RouteDeps"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Create plugins route — GET /plugins
|
||||
|
||||
**Files:**
|
||||
- Create: `src/plugins/api-server/routes/plugins.ts`
|
||||
- Create: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test for GET /plugins**
|
||||
|
||||
Create `src/plugins/api-server/__tests__/routes-plugins.test.ts`:
|
||||
|
||||
```ts
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { createApiServer } from '../server.js'
|
||||
import { TokenStore } from '../auth/token-store.js'
|
||||
import { pluginRoutes } from '../routes/plugins.js'
|
||||
import type { RouteDeps } from '../routes/types.js'
|
||||
import type { LifecycleManager } from '../../../core/plugin/lifecycle-manager.js'
|
||||
import type { PluginRegistry, PluginEntry } from '../../../core/plugin/plugin-registry.js'
|
||||
import type { OpenACPPlugin } from '../../../core/plugin/types.js'
|
||||
import * as fs from 'node:fs'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
|
||||
const SECRET = 'b'.repeat(64)
|
||||
const JWT_SECRET = 'plugin-test-jwt-secret'
|
||||
|
||||
function authHeaders() {
|
||||
return { authorization: `Bearer ${SECRET}` }
|
||||
}
|
||||
|
||||
function makeRegistry(entries: Record<string, Partial<PluginEntry>>): PluginRegistry {
|
||||
return {
|
||||
list: () => new Map(Object.entries(entries).map(([name, e]) => [name, {
|
||||
version: '1.0.0',
|
||||
installedAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
source: 'builtin' as const,
|
||||
enabled: true,
|
||||
settingsPath: '/tmp/settings.json',
|
||||
...e,
|
||||
}])),
|
||||
get: (name: string) => {
|
||||
const e = entries[name]
|
||||
if (!e) return undefined
|
||||
return {
|
||||
version: '1.0.0',
|
||||
installedAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
source: 'builtin' as const,
|
||||
enabled: true,
|
||||
settingsPath: '/tmp/settings.json',
|
||||
...e,
|
||||
}
|
||||
},
|
||||
setEnabled: () => {},
|
||||
remove: () => {},
|
||||
save: async () => {},
|
||||
register: () => {},
|
||||
} as unknown as PluginRegistry
|
||||
}
|
||||
|
||||
function makeLifecycleManager(opts: {
|
||||
registryEntries?: Record<string, Partial<PluginEntry>>
|
||||
loadedPlugins?: string[]
|
||||
failedPlugins?: string[]
|
||||
pluginDefs?: OpenACPPlugin[]
|
||||
instanceRoot?: string
|
||||
bootFn?: (plugins: OpenACPPlugin[]) => Promise<void>
|
||||
unloadFn?: (name: string) => Promise<void>
|
||||
}): LifecycleManager {
|
||||
return {
|
||||
registry: makeRegistry(opts.registryEntries ?? {}),
|
||||
loadedPlugins: opts.loadedPlugins ?? [],
|
||||
failedPlugins: opts.failedPlugins ?? [],
|
||||
plugins: opts.pluginDefs ?? [],
|
||||
instanceRoot: opts.instanceRoot,
|
||||
boot: opts.bootFn ?? (async () => {}),
|
||||
unloadPlugin: opts.unloadFn ?? (async () => {}),
|
||||
} as unknown as LifecycleManager
|
||||
}
|
||||
|
||||
describe('plugin routes', () => {
|
||||
let server: Awaited<ReturnType<typeof createApiServer>> | null = null
|
||||
let tokenStore: TokenStore
|
||||
let tmpDir: string
|
||||
|
||||
async function buildServer(lm: LifecycleManager) {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-routes-test-'))
|
||||
const tokensFile = path.join(tmpDir, 'tokens.json')
|
||||
tokenStore = new TokenStore(tokensFile)
|
||||
await tokenStore.load()
|
||||
|
||||
server = await createApiServer({
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
getSecret: () => SECRET,
|
||||
getJwtSecret: () => JWT_SECRET,
|
||||
tokenStore,
|
||||
})
|
||||
|
||||
const deps: Partial<RouteDeps> = {
|
||||
lifecycleManager: lm,
|
||||
}
|
||||
|
||||
server.registerPlugin('/api/v1/plugins', async (app) => {
|
||||
await pluginRoutes(app, deps as RouteDeps)
|
||||
})
|
||||
|
||||
await server.app.ready()
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) {
|
||||
await server.app.close()
|
||||
server = null
|
||||
}
|
||||
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('GET /api/v1/plugins', () => {
|
||||
it('returns installed plugins with runtime state', async () => {
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/telegram': { source: 'builtin', enabled: true },
|
||||
'@openacp/translator': { source: 'npm', enabled: false },
|
||||
},
|
||||
loadedPlugins: ['@openacp/telegram'],
|
||||
failedPlugins: [],
|
||||
pluginDefs: [
|
||||
{ name: '@openacp/telegram', version: '1.0.0', essential: true, configure: async () => {}, setup: async () => {} } as unknown as OpenACPPlugin,
|
||||
],
|
||||
})
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/plugins',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.plugins).toHaveLength(2)
|
||||
|
||||
const telegram = body.plugins.find((p: any) => p.name === '@openacp/telegram')
|
||||
expect(telegram).toMatchObject({
|
||||
name: '@openacp/telegram',
|
||||
source: 'builtin',
|
||||
enabled: true,
|
||||
loaded: true,
|
||||
failed: false,
|
||||
essential: true,
|
||||
hasConfigure: true,
|
||||
})
|
||||
|
||||
const translator = body.plugins.find((p: any) => p.name === '@openacp/translator')
|
||||
expect(translator).toMatchObject({
|
||||
name: '@openacp/translator',
|
||||
source: 'npm',
|
||||
enabled: false,
|
||||
loaded: false,
|
||||
failed: false,
|
||||
essential: false,
|
||||
hasConfigure: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 401 without auth', async () => {
|
||||
await buildServer(makeLifecycleManager({}))
|
||||
const res = await server!.app.inject({ method: 'GET', url: '/api/v1/plugins' })
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/code/openacp-workspace/OpenACP
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts 2>&1 | head -20
|
||||
```
|
||||
|
||||
Expected: FAIL — `Cannot find module '../routes/plugins.js'`
|
||||
|
||||
- [ ] **Step 3: Create plugins route with GET /plugins**
|
||||
|
||||
Create `src/plugins/api-server/routes/plugins.ts`:
|
||||
|
||||
```ts
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
import { requireScopes } from '../middleware/auth.js'
|
||||
import { corePlugins } from '../../../plugins/core-plugins.js'
|
||||
|
||||
export async function pluginRoutes(
|
||||
app: FastifyInstance,
|
||||
deps: RouteDeps,
|
||||
): Promise<void> {
|
||||
const { lifecycleManager } = deps
|
||||
const admin = [requireScopes('system:admin')]
|
||||
|
||||
// GET /plugins — list all installed plugins with runtime state
|
||||
app.get('/', { preHandler: admin }, async () => {
|
||||
if (!lifecycleManager?.registry) return { plugins: [] }
|
||||
|
||||
const registry = lifecycleManager.registry
|
||||
const loadedSet = new Set(lifecycleManager.loadedPlugins)
|
||||
const failedSet = new Set(lifecycleManager.failedPlugins)
|
||||
const loadOrderMap = new Map(lifecycleManager.plugins.map((p) => [p.name, p]))
|
||||
const coreMap = new Map(corePlugins.map((p) => [p.name, p]))
|
||||
|
||||
const plugins = Array.from(registry.list().entries()).map(([name, entry]) => {
|
||||
const def = loadOrderMap.get(name) ?? coreMap.get(name)
|
||||
return {
|
||||
name,
|
||||
version: entry.version,
|
||||
description: entry.description,
|
||||
source: entry.source,
|
||||
enabled: entry.enabled,
|
||||
loaded: loadedSet.has(name),
|
||||
failed: failedSet.has(name),
|
||||
essential: def?.essential ?? false,
|
||||
hasConfigure: typeof def?.configure === 'function',
|
||||
}
|
||||
})
|
||||
|
||||
return { plugins }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify GET /plugins passes**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗|PASS|FAIL|GET /api"
|
||||
```
|
||||
|
||||
Expected: both GET /plugins tests pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
|
||||
git commit -m "feat(api-server): add GET /plugins endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: GET /plugins/marketplace
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/plugins.ts`
|
||||
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests for marketplace**
|
||||
|
||||
Add to the `describe('plugin routes')` block in the test file:
|
||||
|
||||
```ts
|
||||
describe('GET /api/v1/plugins/marketplace', () => {
|
||||
it('returns marketplace plugins with installed flag', async () => {
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/telegram': { source: 'builtin', enabled: true },
|
||||
},
|
||||
})
|
||||
await buildServer(lm)
|
||||
|
||||
// Mock the RegistryClient by intercepting the dynamic import
|
||||
// We can test via the actual fetch, but for unit test we rely on
|
||||
// the 503 path when the registry is unreachable.
|
||||
const res = await server!.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/plugins/marketplace',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
// Registry fetch will fail in test env (no internet) — expect 503
|
||||
expect(res.statusCode).toBe(503)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.error).toBe('Marketplace unavailable')
|
||||
})
|
||||
|
||||
it('returns 401 without auth', async () => {
|
||||
await buildServer(makeLifecycleManager({}))
|
||||
const res = await server!.app.inject({ method: 'GET', url: '/api/v1/plugins/marketplace' })
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify new tests fail**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗|marketplace"
|
||||
```
|
||||
|
||||
Expected: FAIL — marketplace route not yet registered.
|
||||
|
||||
- [ ] **Step 3: Add GET /plugins/marketplace to plugins.ts**
|
||||
|
||||
Append to `pluginRoutes` function in `src/plugins/api-server/routes/plugins.ts`:
|
||||
|
||||
```ts
|
||||
// GET /plugins/marketplace — proxy to RegistryClient with installed flag
|
||||
app.get('/marketplace', { preHandler: admin }, async (_req, reply) => {
|
||||
try {
|
||||
const { RegistryClient } = await import('../../../core/plugin/registry-client.js')
|
||||
const client = new RegistryClient()
|
||||
const data = await client.getRegistry()
|
||||
|
||||
const installedNames = new Set(
|
||||
lifecycleManager?.registry
|
||||
? Array.from(lifecycleManager.registry.list().keys())
|
||||
: [],
|
||||
)
|
||||
|
||||
const plugins = data.plugins.map((p) => ({
|
||||
...p,
|
||||
installed: installedNames.has(p.name) || installedNames.has(p.npm),
|
||||
}))
|
||||
|
||||
return { plugins, categories: data.categories }
|
||||
} catch {
|
||||
return reply.status(503).send({ error: 'Marketplace unavailable' })
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
|
||||
```
|
||||
|
||||
Expected: all 4 tests pass (GET /plugins ×2, marketplace ×2).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
|
||||
git commit -m "feat(api-server): add GET /plugins/marketplace endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: POST /plugins/:name/enable
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/plugins.ts`
|
||||
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests**
|
||||
|
||||
Add to the test file:
|
||||
|
||||
```ts
|
||||
describe('POST /api/v1/plugins/:name/enable', () => {
|
||||
it('enables and boots a disabled builtin plugin', async () => {
|
||||
let booted: string[] = []
|
||||
let registryEnabled: Record<string, boolean> = {}
|
||||
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/context': { source: 'builtin', enabled: false },
|
||||
},
|
||||
loadedPlugins: [],
|
||||
pluginDefs: [],
|
||||
bootFn: async (plugins) => { booted = plugins.map(p => p.name) },
|
||||
})
|
||||
;(lm.registry as any).setEnabled = (name: string, val: boolean) => { registryEnabled[name] = val }
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Fcontext/enable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
it('is idempotent when plugin is already loaded', async () => {
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/context': { source: 'builtin', enabled: true },
|
||||
},
|
||||
loadedPlugins: ['@openacp/context'],
|
||||
})
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Fcontext/enable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
})
|
||||
|
||||
it('returns 404 for unknown plugin', async () => {
|
||||
await buildServer(makeLifecycleManager({}))
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Funknown/enable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(404)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify tests fail**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "enable|✓|✗"
|
||||
```
|
||||
|
||||
Expected: FAIL — route not yet implemented.
|
||||
|
||||
- [ ] **Step 3: Add POST /:name/enable to plugins.ts**
|
||||
|
||||
Append to `pluginRoutes`:
|
||||
|
||||
```ts
|
||||
// POST /plugins/:name/enable — hot-load a disabled plugin
|
||||
app.post('/:name/enable', { preHandler: admin }, async (req, reply) => {
|
||||
if (!lifecycleManager?.registry) {
|
||||
return reply.status(503).send({ error: 'Plugin manager unavailable' })
|
||||
}
|
||||
|
||||
const name = decodeURIComponent((req.params as { name: string }).name)
|
||||
const registry = lifecycleManager.registry
|
||||
const entry = registry.get(name)
|
||||
|
||||
if (!entry) {
|
||||
return reply.status(404).send({ error: `Plugin "${name}" not found` })
|
||||
}
|
||||
|
||||
// Idempotent — already loaded
|
||||
if (lifecycleManager.loadedPlugins.includes(name)) {
|
||||
registry.setEnabled(name, true)
|
||||
await registry.save()
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
// Resolve plugin definition
|
||||
let pluginDef = lifecycleManager.plugins.find((p) => p.name === name)
|
||||
|
||||
if (!pluginDef) {
|
||||
if (entry.source === 'builtin') {
|
||||
pluginDef = corePlugins.find((p) => p.name === name)
|
||||
} else {
|
||||
// npm / local — dynamic import
|
||||
const { importFromDir } = await import('../../../core/plugin/plugin-installer.js')
|
||||
const instanceRoot =
|
||||
lifecycleManager.instanceRoot ??
|
||||
(await import('node:path')).default.join(
|
||||
(await import('node:os')).default.homedir(),
|
||||
'.openacp',
|
||||
)
|
||||
const pluginsDir = (await import('node:path')).default.join(instanceRoot, 'plugins')
|
||||
try {
|
||||
const mod = await importFromDir(name, pluginsDir)
|
||||
pluginDef = mod.default ?? mod
|
||||
} catch {
|
||||
return reply
|
||||
.status(500)
|
||||
.send({ error: 'Plugin module could not be loaded. Try restarting the server.' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!pluginDef) {
|
||||
return reply.status(500).send({ error: `Plugin definition not found for "${name}"` })
|
||||
}
|
||||
|
||||
registry.setEnabled(name, true)
|
||||
await registry.save()
|
||||
|
||||
await lifecycleManager.boot([pluginDef])
|
||||
|
||||
if (lifecycleManager.failedPlugins.includes(name)) {
|
||||
return reply.status(500).send({ error: `Plugin "${name}" failed to start` })
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
|
||||
```
|
||||
|
||||
Expected: all enable tests pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
|
||||
git commit -m "feat(api-server): add POST /plugins/:name/enable endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: POST /plugins/:name/disable
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/plugins.ts`
|
||||
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests**
|
||||
|
||||
Add to the test file:
|
||||
|
||||
```ts
|
||||
describe('POST /api/v1/plugins/:name/disable', () => {
|
||||
it('unloads and disables a loaded plugin', async () => {
|
||||
let unloaded: string[] = []
|
||||
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/context': { source: 'builtin', enabled: true },
|
||||
},
|
||||
loadedPlugins: ['@openacp/context'],
|
||||
pluginDefs: [
|
||||
{ name: '@openacp/context', version: '1.0.0', essential: false, setup: async () => {} } as unknown as OpenACPPlugin,
|
||||
],
|
||||
unloadFn: async (name) => { unloaded.push(name) },
|
||||
})
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Fcontext/disable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
|
||||
expect(unloaded).toContain('@openacp/context')
|
||||
})
|
||||
|
||||
it('returns 409 for essential plugin', async () => {
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/telegram': { source: 'builtin', enabled: true },
|
||||
},
|
||||
loadedPlugins: ['@openacp/telegram'],
|
||||
pluginDefs: [
|
||||
{ name: '@openacp/telegram', version: '1.0.0', essential: true, setup: async () => {} } as unknown as OpenACPPlugin,
|
||||
],
|
||||
})
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Ftelegram/disable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(409)
|
||||
expect(JSON.parse(res.body).error).toContain('Essential')
|
||||
})
|
||||
|
||||
it('returns 404 for unknown plugin', async () => {
|
||||
await buildServer(makeLifecycleManager({}))
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/plugins/@openacp%2Funknown/disable',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(404)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify tests fail**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "disable|✓|✗"
|
||||
```
|
||||
|
||||
Expected: FAIL — route not yet implemented.
|
||||
|
||||
- [ ] **Step 3: Add POST /:name/disable to plugins.ts**
|
||||
|
||||
Append to `pluginRoutes`:
|
||||
|
||||
```ts
|
||||
// POST /plugins/:name/disable — unload and disable a plugin
|
||||
app.post('/:name/disable', { preHandler: admin }, async (req, reply) => {
|
||||
if (!lifecycleManager?.registry) {
|
||||
return reply.status(503).send({ error: 'Plugin manager unavailable' })
|
||||
}
|
||||
|
||||
const name = decodeURIComponent((req.params as { name: string }).name)
|
||||
const registry = lifecycleManager.registry
|
||||
const entry = registry.get(name)
|
||||
|
||||
if (!entry) {
|
||||
return reply.status(404).send({ error: `Plugin "${name}" not found` })
|
||||
}
|
||||
|
||||
// Check essential — look in loadOrder first, fall back to corePlugins
|
||||
const def =
|
||||
lifecycleManager.plugins.find((p) => p.name === name) ??
|
||||
corePlugins.find((p) => p.name === name)
|
||||
|
||||
if (def?.essential) {
|
||||
return reply.status(409).send({ error: 'Essential plugins cannot be disabled' })
|
||||
}
|
||||
|
||||
await lifecycleManager.unloadPlugin(name)
|
||||
registry.setEnabled(name, false)
|
||||
await registry.save()
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "✓|✗"
|
||||
```
|
||||
|
||||
Expected: all disable tests pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
|
||||
git commit -m "feat(api-server): add POST /plugins/:name/disable endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: DELETE /plugins/:name (uninstall)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/routes/plugins.ts`
|
||||
- Modify: `src/plugins/api-server/__tests__/routes-plugins.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write failing tests**
|
||||
|
||||
Add to the test file:
|
||||
|
||||
```ts
|
||||
describe('DELETE /api/v1/plugins/:name', () => {
|
||||
it('unloads and removes an npm plugin', async () => {
|
||||
let unloaded: string[] = []
|
||||
let removed: string[] = []
|
||||
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/translator': { source: 'npm', enabled: true },
|
||||
},
|
||||
loadedPlugins: ['@openacp/translator'],
|
||||
unloadFn: async (name) => { unloaded.push(name) },
|
||||
})
|
||||
;(lm.registry as any).remove = (name: string) => { removed.push(name) }
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/plugins/@openacp%2Ftranslator',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(JSON.parse(res.body)).toMatchObject({ ok: true })
|
||||
expect(unloaded).toContain('@openacp/translator')
|
||||
expect(removed).toContain('@openacp/translator')
|
||||
})
|
||||
|
||||
it('returns 400 for builtin plugin', async () => {
|
||||
const lm = makeLifecycleManager({
|
||||
registryEntries: {
|
||||
'@openacp/telegram': { source: 'builtin', enabled: true },
|
||||
},
|
||||
})
|
||||
|
||||
await buildServer(lm)
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/plugins/@openacp%2Ftelegram',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(400)
|
||||
expect(JSON.parse(res.body).error).toContain('Builtin')
|
||||
})
|
||||
|
||||
it('returns 404 for unknown plugin', async () => {
|
||||
await buildServer(makeLifecycleManager({}))
|
||||
|
||||
const res = await server!.app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/plugins/@openacp%2Funknown',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(404)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify tests fail**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose 2>&1 | grep -E "DELETE|uninstall|✓|✗"
|
||||
```
|
||||
|
||||
Expected: FAIL — route not yet implemented.
|
||||
|
||||
- [ ] **Step 3: Add DELETE /:name to plugins.ts**
|
||||
|
||||
Append to `pluginRoutes`:
|
||||
|
||||
```ts
|
||||
// DELETE /plugins/:name — uninstall (remove from registry, unload)
|
||||
app.delete('/:name', { preHandler: admin }, async (req, reply) => {
|
||||
if (!lifecycleManager?.registry) {
|
||||
return reply.status(503).send({ error: 'Plugin manager unavailable' })
|
||||
}
|
||||
|
||||
const name = decodeURIComponent((req.params as { name: string }).name)
|
||||
const registry = lifecycleManager.registry
|
||||
const entry = registry.get(name)
|
||||
|
||||
if (!entry) {
|
||||
return reply.status(404).send({ error: `Plugin "${name}" not found` })
|
||||
}
|
||||
|
||||
if (entry.source === 'builtin') {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: 'Builtin plugins cannot be uninstalled. Use disable instead.' })
|
||||
}
|
||||
|
||||
await lifecycleManager.unloadPlugin(name)
|
||||
registry.remove(name)
|
||||
await registry.save()
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run all plugin route tests**
|
||||
|
||||
```bash
|
||||
pnpm test src/plugins/api-server/__tests__/routes-plugins.test.ts --reporter=verbose
|
||||
```
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/routes/plugins.ts src/plugins/api-server/__tests__/routes-plugins.test.ts
|
||||
git commit -m "feat(api-server): add DELETE /plugins/:name endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Register plugins route in api-server/index.ts
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/plugins/api-server/index.ts`
|
||||
|
||||
- [ ] **Step 1: Wire lifecycleManager into RouteDeps and register the route**
|
||||
|
||||
In `src/plugins/api-server/index.ts`, find the `setup(ctx)` function. After the existing imports and before `const deps: RouteDeps = {`:
|
||||
|
||||
Add import at top of the setup function (alongside the other route imports):
|
||||
|
||||
```ts
|
||||
const { pluginRoutes } = await import('./routes/plugins.js')
|
||||
```
|
||||
|
||||
Add `lifecycleManager` to the deps object:
|
||||
|
||||
```ts
|
||||
const deps: RouteDeps = {
|
||||
core,
|
||||
topicManager,
|
||||
startedAt,
|
||||
getVersion,
|
||||
commandRegistry,
|
||||
authPreHandler: routeAuthPreHandler,
|
||||
contextManager,
|
||||
lifecycleManager: core.lifecycleManager, // ← add this line
|
||||
}
|
||||
```
|
||||
|
||||
Register the route after the existing `server.registerPlugin` calls:
|
||||
|
||||
```ts
|
||||
server.registerPlugin('/api/v1/plugins', async (app) => pluginRoutes(app, deps))
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run full test suite to check for regressions**
|
||||
|
||||
```bash
|
||||
cd /Users/lucas/code/openacp-workspace/OpenACP
|
||||
pnpm test 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: all tests pass, no regressions.
|
||||
|
||||
- [ ] **Step 3: Build to verify TypeScript**
|
||||
|
||||
```bash
|
||||
pnpm build 2>&1 | grep -E "error|Error" | head -10
|
||||
```
|
||||
|
||||
Expected: no errors.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/plugins/api-server/index.ts
|
||||
git commit -m "feat(api-server): register /api/v1/plugins route group"
|
||||
```
|
||||
1811
docs/superpowers/plans/2026-04-03-security-hardening.md
Normal file
1811
docs/superpowers/plans/2026-04-03-security-hardening.md
Normal file
File diff suppressed because it is too large
Load Diff
504
docs/superpowers/plans/2026-04-03-session-list-history.md
Normal file
504
docs/superpowers/plans/2026-04-03-session-list-history.md
Normal file
@ -0,0 +1,504 @@
|
||||
# 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"
|
||||
```
|
||||
508
docs/superpowers/plans/2026-04-04-file-attachment-api.md
Normal file
508
docs/superpowers/plans/2026-04-04-file-attachment-api.md
Normal file
@ -0,0 +1,508 @@
|
||||
# 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"
|
||||
```
|
||||
1396
docs/superpowers/plans/2026-04-05-config-legacy-removal.md
Normal file
1396
docs/superpowers/plans/2026-04-05-config-legacy-removal.md
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,896 @@
|
||||
# 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"
|
||||
```
|
||||
550
docs/superpowers/plans/2026-04-07-telegram-custom-path-wizard.md
Normal file
550
docs/superpowers/plans/2026-04-07-telegram-custom-path-wizard.md
Normal file
@ -0,0 +1,550 @@
|
||||
# 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)} <workspace-path></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"
|
||||
```
|
||||
@ -0,0 +1,374 @@
|
||||
# Codebase Logic Review — Findings
|
||||
|
||||
**Date:** 2026-03-27
|
||||
**Scope:** Full codebase review — core, plugins, adapter primitives, utilities
|
||||
**Status:** Review complete — awaiting triage
|
||||
|
||||
---
|
||||
|
||||
## Previously Identified Issues (from spec) — All Fixed
|
||||
|
||||
The 7 issues from `2026-03-27-codebase-logic-review-design.md` have all been implemented:
|
||||
1. PermissionGate `setPending()` superseding — fixed
|
||||
2. AgentInstance `destroy()` waiting for exit — fixed
|
||||
3. SessionBridge `handleAgentEvent()` error handling — fixed
|
||||
4. CommandRegistry `unregister()` dead code — fixed
|
||||
5. MiddlewareChain pre-sorted at `add()` time — fixed
|
||||
6. AgentInstance crash detection for signal kills — fixed
|
||||
7. NotificationManager error catching — fixed
|
||||
|
||||
---
|
||||
|
||||
## New Issues Found
|
||||
|
||||
### HIGH Severity
|
||||
|
||||
#### H1. Session `processPrompt` throws unrecoverably if session is "finished"
|
||||
|
||||
**File:** `src/core/sessions/session.ts:179-181`
|
||||
|
||||
**Issue:** If a session is in "finished" state and a queued prompt still executes (enqueued just before `finish()` was called), `this.activate()` throws because `finished -> active` is invalid. The PromptQueue error handler calls `session.fail()`, but `finished -> error` is also invalid — causing a **second throw** that becomes an unhandled exception.
|
||||
|
||||
**Fix:** Guard at top of `processPrompt`:
|
||||
```typescript
|
||||
if (this._status === "finished") return;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### H2. `cancelSession` can throw if agent error transitions state before `markCancelled()`
|
||||
|
||||
**File:** `src/core/sessions/session-manager.ts:118-122`
|
||||
|
||||
**Issue:** `session.abortPrompt()` can trigger the agent to emit an error, calling `session.fail()` which transitions to "error" state. Then `markCancelled()` attempts `error -> cancelled`, which is invalid in the state machine (`error` can only go to `active`). This throws an uncaught exception.
|
||||
|
||||
**Fix:** Either:
|
||||
- Add "cancelled" to valid transitions from "error" state
|
||||
- Wrap `markCancelled()` in try-catch
|
||||
- Check session status before calling `markCancelled()`
|
||||
|
||||
---
|
||||
|
||||
#### H3. ConfigManager `save()` writes invalid config to disk, bricks next startup
|
||||
|
||||
**File:** `src/core/config/config.ts:260-283`
|
||||
|
||||
**Issue:** `save()` writes the merged config to disk **before** re-validating with Zod. If validation fails, the invalid config is already on disk. Next startup reads this invalid config and calls `process.exit(1)`.
|
||||
|
||||
**Fix:** Validate BEFORE writing to disk. If validation fails, log an error and don't write.
|
||||
|
||||
---
|
||||
|
||||
#### H4. Session logger leaks file descriptors — `pino.destination` never closed
|
||||
|
||||
**File:** `src/core/utils/log.ts:160-210`
|
||||
|
||||
**Issue:** Each session creates a `pino.destination(sessionLogPath)` which opens a file descriptor. The destination is stored as `__sessionDest` but never closed. Long-running servers with many sessions will exhaust OS file descriptor limits.
|
||||
|
||||
**Fix:** Add a `closeSessionLogger()` function called during `session.destroy()`:
|
||||
```typescript
|
||||
export function closeSessionLogger(logger: Logger): void {
|
||||
const dest = (logger as any).__sessionDest
|
||||
if (dest && typeof dest.destroy === 'function') {
|
||||
dest.destroy()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### H5. ActivityTracker: thinking indicator stuck when `maxThinkingDuration` exceeded
|
||||
|
||||
**File:** `src/core/adapter-primitives/primitives/activity-tracker.ts:74-76`
|
||||
|
||||
**Issue:** When `maxThinkingDuration` is exceeded, `stopRefresh` is called (stops the interval timer), but `removeThinkingIndicator()` is **never called**. The thinking indicator remains visible to the user indefinitely.
|
||||
|
||||
**Fix:**
|
||||
```typescript
|
||||
if (Date.now() - state.startTime >= this.config.maxThinkingDuration) {
|
||||
state.dismissed = true
|
||||
this.stopRefresh(state)
|
||||
state.callbacks.removeThinkingIndicator().catch(() => {})
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### H6. `main.ts`: spinner/logger not cleaned up on plugin boot failure
|
||||
|
||||
**File:** `src/main.ts:119-272`
|
||||
|
||||
**Issue:** If `core.lifecycleManager.boot()` throws, the spinner keeps spinning and logger stays muted (from `muteLogger()`). The error catch at line 270 logs the error, but the muted logger swallows it. The user sees a spinning animation and no error message, then `process.exit(1)`.
|
||||
|
||||
**Fix:** Stop spinner and unmute logger in the catch block:
|
||||
```typescript
|
||||
} catch (err) {
|
||||
if (spinner) spinner.fail('Plugin boot failed')
|
||||
unmuteLogger()
|
||||
log.error({ err }, 'Plugin boot failed')
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### MEDIUM Severity
|
||||
|
||||
#### M1. Agent crash during auto-naming silently discards error event
|
||||
|
||||
**File:** `src/core/sessions/session.ts:363-396`
|
||||
|
||||
**Issue:** During `autoName()`, the session emitter is paused and a capture handler only catches "text" events (line 370). If the agent crashes during auto-naming, the crash error event is buffered. Then `clearBuffer()` at line 393 **discards all buffered events**, including the crash error. The user never sees the crash notification.
|
||||
|
||||
**Fix:** In `autoName()` finally block, replay error-type events instead of clearing all:
|
||||
```typescript
|
||||
// Replay error events, discard others
|
||||
const buffer = this.getBuffer() // need to expose buffer
|
||||
for (const { event, args } of buffer) {
|
||||
if (event === 'agent_event') {
|
||||
const agentEvent = args[0] as AgentEvent
|
||||
if (agentEvent?.type === 'error') {
|
||||
this.emit('agent_event', agentEvent)
|
||||
}
|
||||
}
|
||||
}
|
||||
this.clearBuffer()
|
||||
this.resume()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### M2. PermissionGate timeout timer not `unref()`ed — blocks graceful shutdown
|
||||
|
||||
**File:** `src/core/sessions/permission-gate.ts:33-36`
|
||||
|
||||
**Issue:** The 10-minute timeout timer keeps the Node.js event loop alive. During graceful shutdown with an active permission request, the process won't exit for up to 10 minutes.
|
||||
|
||||
**Fix:** Add `unref()` after setting the timer (pattern already used in `agent-instance.ts:753`):
|
||||
```typescript
|
||||
this.timeoutTimer = setTimeout(() => {
|
||||
this.reject("Permission request timed out");
|
||||
}, this.timeoutMs);
|
||||
if (typeof this.timeoutTimer === 'object' && 'unref' in this.timeoutTimer) {
|
||||
(this.timeoutTimer as NodeJS.Timeout).unref();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### M3. Lazy resume resurrects truly-finished sessions after restart
|
||||
|
||||
**File:** `src/core/core.ts:603-688`
|
||||
|
||||
**Issue:** On shutdown, ALL sessions are marked as `status: "finished"` in `shutdownAll()`. On restart, when a user messages in a thread of a truly-completed session, `lazyResume` spawns a new agent for it. The user may not expect their completed session to restart.
|
||||
|
||||
**Fix:** Either:
|
||||
- Skip `status === "finished"` in `lazyResume`
|
||||
- Use a separate status like `"shutdown"` for sessions that were active at shutdown time
|
||||
|
||||
---
|
||||
|
||||
#### M4. `SessionBridge.sendMessage` — middleware errors become unhandled rejections
|
||||
|
||||
**File:** `src/core/sessions/session-bridge.ts:40-53`
|
||||
|
||||
**Issue:** `sendMessage` is async but called without `await` in `handleAgentEvent`. The `mw.execute()` call is awaited within `sendMessage`, and if middleware throws, it propagates as an unhandled promise rejection.
|
||||
|
||||
**Fix:** Add `.catch()` to `sendMessage` calls in `handleAgentEvent`, or wrap the entire `sendMessage` body in try-catch.
|
||||
|
||||
---
|
||||
|
||||
#### M5. `handleCleanup` doesn't cancel active sessions before deleting records
|
||||
|
||||
**File:** `src/plugins/telegram/commands/session.ts:167-201`
|
||||
|
||||
**Issue:** `handleCleanup` deletes session records without first cancelling running agent processes. Compare with `handleCleanupEverythingConfirmed` which correctly calls `cancelSession` before removal. This can orphan running agent subprocesses.
|
||||
|
||||
**Fix:** Add active session cancellation before record removal, similar to `handleCleanupEverythingConfirmed`.
|
||||
|
||||
---
|
||||
|
||||
#### M6. Tunnel providers don't wait for child process exit on `stop()`
|
||||
|
||||
**Files:** All tunnel providers (`cloudflare.ts`, `ngrok.ts`, `bore.ts`, `tailscale.ts`)
|
||||
|
||||
**Issue:** All providers call `this.child.kill('SIGTERM')` and immediately set `this.child = null` without waiting for exit. If a new tunnel is started immediately on the same port, the old process may still be holding it.
|
||||
|
||||
**Fix:** Wait for the `exit` event with a SIGKILL timeout fallback.
|
||||
|
||||
---
|
||||
|
||||
#### M7. `CheckpointReader` uses `execFileSync` blocking the event loop
|
||||
|
||||
**File:** `src/plugins/context/entire/checkpoint-reader.ts:43-51`
|
||||
|
||||
**Issue:** The `git()` method uses `execFileSync`, blocking the Node.js event loop. `resolveLatest` iterates all checkpoints with synchronous git calls. Repositories with many checkpoints can freeze all operations for seconds.
|
||||
|
||||
**Fix:** Use `execFile` with `util.promisify` instead of `execFileSync`.
|
||||
|
||||
---
|
||||
|
||||
#### M8. `PermissionHandler` pending map grows unboundedly (memory leak)
|
||||
|
||||
**File:** `src/plugins/telegram/permissions.ts:18, 32`
|
||||
|
||||
**Issue:** The `pending` Map stores entries for every permission request sent. Entries are only removed when the user clicks a button. If ignored, entries stay in memory forever.
|
||||
|
||||
**Fix:** Add TTL-based cleanup (e.g., remove entries older than 10 minutes).
|
||||
|
||||
---
|
||||
|
||||
#### M9. `createBridge` throws if notification/file-service plugins not loaded
|
||||
|
||||
**File:** `src/core/core.ts:693-702`
|
||||
|
||||
**Issue:** `createBridge()` accesses `this.notificationManager` and `this.fileService` via `getService()` which throws if not registered. If these plugins failed to load, all session creation crashes.
|
||||
|
||||
**Fix:** Use optional service lookups that return `undefined` instead of throwing.
|
||||
|
||||
---
|
||||
|
||||
#### M10. Draft `flush()` race condition — concurrent flushes can create duplicate messages
|
||||
|
||||
**File:** `src/core/adapter-primitives/primitives/draft-manager.ts:59-79`
|
||||
|
||||
**Issue:** `finalize()` awaits `flushPromise` then calls `flush()`, but a timer-triggered flush can sneak in between. If both are first-flushes (no `_messageId` yet), both create separate messages.
|
||||
|
||||
**Fix:** Chain the finalize flush onto `flushPromise`:
|
||||
```typescript
|
||||
this.flushPromise = this.flushPromise.then(() => this.buffer ? this.flush() : undefined)
|
||||
await this.flushPromise
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### M11. Node stream adapters don't implement close/cancel — resource leaks
|
||||
|
||||
**File:** `src/core/utils/streams.ts:3-26`
|
||||
|
||||
**Issue:** `nodeToWebWritable` doesn't implement `close()` or `abort()`. `nodeToWebReadable` doesn't implement `cancel()`. When Web streams are closed/cancelled, the underlying Node streams stay open, leaking file handles/sockets.
|
||||
|
||||
**Fix:** Add the missing handlers:
|
||||
```typescript
|
||||
// WritableStream
|
||||
close() { nodeStream.end() },
|
||||
abort(reason) { nodeStream.destroy(reason instanceof Error ? reason : new Error(String(reason))) }
|
||||
|
||||
// ReadableStream
|
||||
cancel() { nodeStream.destroy() }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### LOW Severity
|
||||
|
||||
#### L1. `SecurityGuard.checkAccess` TOCTOU race on session count
|
||||
|
||||
**File:** `src/plugins/security/security-guard.ts:22-27`
|
||||
|
||||
**Issue:** Session count checked at access time, but session created after check passes. Two concurrent messages can both pass the check, exceeding `maxConcurrentSessions` by 1.
|
||||
|
||||
**Verdict:** Acceptable for current use case. Note if session limits become critical.
|
||||
|
||||
---
|
||||
|
||||
#### L2. `core.ts` `patchRecord` not awaited — potential unhandled rejection
|
||||
|
||||
**File:** `src/core/core.ts:293-295`
|
||||
|
||||
**Issue:** `patchRecord` returns Promise but is not awaited. Store write failures become unhandled rejections.
|
||||
|
||||
**Fix:** Add `.catch()` or await.
|
||||
|
||||
---
|
||||
|
||||
#### L3. PluginContext `cleanup()` service unregistration order
|
||||
|
||||
**File:** `src/core/plugin/plugin-context.ts:179-200`
|
||||
|
||||
**Issue:** Services are unregistered (line 190) before command registry is accessed (line 193). If the command-registry was registered by the same plugin being cleaned up, commands are never cleaned.
|
||||
|
||||
**Fix:** Move command cleanup before service unregistration.
|
||||
|
||||
---
|
||||
|
||||
#### L4. SendQueue timer not cleared on `clear()` — temporary message stall
|
||||
|
||||
**File:** `src/core/adapter-primitives/primitives/send-queue.ts:85-106`
|
||||
|
||||
**Issue:** `clear()` doesn't cancel the pending setTimeout. New items enqueued between `clear()` and the timer firing won't be processed until the orphaned timer fires.
|
||||
|
||||
**Fix:** Track and clear the timer in `clear()`.
|
||||
|
||||
---
|
||||
|
||||
#### L5. `downloadFile` unlimited redirect following
|
||||
|
||||
**File:** `src/core/utils/install-binary.ts:24-64`
|
||||
|
||||
**Issue:** Follows 301/302 redirects recursively with no limit. A misconfigured server could cause stack overflow.
|
||||
|
||||
**Fix:** Add `maxRedirects` parameter (default 10).
|
||||
|
||||
---
|
||||
|
||||
#### L6. `main.ts` `fs.watch` watcher never closed on shutdown
|
||||
|
||||
**File:** `src/main.ts:224-243`
|
||||
|
||||
**Issue:** Dev plugin hot-reload watcher is never stored or closed during shutdown. Keeps process alive or causes errors after cleanup.
|
||||
|
||||
**Fix:** Store the watcher and close it during shutdown.
|
||||
|
||||
---
|
||||
|
||||
#### L7. `SpeechService.refreshProviders` doesn't remove stale factory providers
|
||||
|
||||
**File:** `src/plugins/speech/speech-service.ts:68-80`
|
||||
|
||||
**Issue:** When config changes remove a provider, the old factory-created provider remains registered. Merge only adds/overwrites, never removes factory providers.
|
||||
|
||||
**Fix:** Track factory-created vs externally-registered providers. Clear factory providers before re-adding.
|
||||
|
||||
---
|
||||
|
||||
#### L8. `ContextCache` constructor creates directory synchronously — crashes on permission error
|
||||
|
||||
**File:** `src/plugins/context/context-cache.ts:10`
|
||||
|
||||
**Issue:** `fs.mkdirSync` in constructor throws synchronously on permission errors, crashing the application during plugin boot.
|
||||
|
||||
**Fix:** Wrap in try-catch or defer to first use.
|
||||
|
||||
---
|
||||
|
||||
#### L9. PromptQueue race — enqueue during `clear()` can bypass the clear
|
||||
|
||||
**File:** `src/core/sessions/prompt-queue.ts:55-65`
|
||||
|
||||
**Issue:** Narrow window where `enqueue()` between `clear()` resolving pending items and `finally` block running `drainNext()` causes a prompt to execute after cancel was requested.
|
||||
|
||||
**Fix:** Add a generation counter checked in `drainNext()`.
|
||||
|
||||
---
|
||||
|
||||
## Summary by Priority
|
||||
|
||||
| Priority | Count | Issues |
|
||||
|----------|-------|--------|
|
||||
| **HIGH** | 6 | H1, H2, H3, H4, H5, H6 |
|
||||
| **MEDIUM** | 11 | M1-M11 |
|
||||
| **LOW** | 9 | L1-L9 |
|
||||
|
||||
### Recommended Fix Order
|
||||
|
||||
1. **H1** — Session processPrompt finished-state crash (trivial 1-line guard)
|
||||
2. **H2** — cancelSession state machine throw (add valid transition or guard)
|
||||
3. **H5** — Thinking indicator stuck forever (3-line fix)
|
||||
4. **H6** — Boot failure invisible to user (add spinner/unmute cleanup)
|
||||
5. **H3** — Config save bricks startup (validate before write)
|
||||
6. **H4** — Session logger fd leak (add close function)
|
||||
7. **M2** — PermissionGate timer unref (2-line fix)
|
||||
8. **M4** — sendMessage unhandled rejections (add .catch())
|
||||
9. **M1** — Auto-name swallows crash errors (replay errors from buffer)
|
||||
10. Rest of MEDIUM/LOW based on impact
|
||||
246
docs/superpowers/specs/2026-04-02-cli-json-output-design.md
Normal file
246
docs/superpowers/specs/2026-04-02-cli-json-output-design.md
Normal file
@ -0,0 +1,246 @@
|
||||
# CLI `--json` Output Standardization
|
||||
|
||||
## Overview
|
||||
|
||||
Add standardized `--json` flag support across all CLI commands that return structured data or action results. When `--json` is passed, the command outputs a single line of JSON to stdout and exits with an appropriate exit code. This enables automation, scripting, and app integration.
|
||||
|
||||
## JSON Envelope
|
||||
|
||||
All commands use a consistent envelope:
|
||||
|
||||
**Success (exit 0):**
|
||||
```json
|
||||
{ "success": true, "data": { ... } }
|
||||
```
|
||||
|
||||
**Error (exit non-zero):**
|
||||
```json
|
||||
{ "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable description" } }
|
||||
```
|
||||
|
||||
Rules:
|
||||
- Output is always a single line of valid JSON on stdout
|
||||
- Exit code 0 for success, non-zero for errors
|
||||
- No ANSI escape codes, progress bars, spinners, or other text in stdout when `--json` is active
|
||||
|
||||
## Core Module: `src/cli/output.ts`
|
||||
|
||||
### Types
|
||||
|
||||
```typescript
|
||||
interface JsonSuccess<T = unknown> {
|
||||
success: true;
|
||||
data: T;
|
||||
}
|
||||
|
||||
interface JsonError {
|
||||
success: false;
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
|
||||
type JsonOutput<T = unknown> = JsonSuccess<T> | JsonError;
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
```typescript
|
||||
function isJsonMode(args: string[]): boolean;
|
||||
function jsonSuccess(data: unknown): never; // JSON to stdout + process.exit(0)
|
||||
function jsonError(code: string, message: string): never; // JSON to stdout + process.exit(1)
|
||||
function muteForJson(): void; // Mute pino logger to suppress stderr noise
|
||||
```
|
||||
|
||||
`jsonSuccess` and `jsonError` are terminal — they call `process.exit()` and never return. This naturally prevents any subsequent `console.log` noise.
|
||||
|
||||
### Error Codes
|
||||
|
||||
```typescript
|
||||
const ErrorCodes = {
|
||||
DAEMON_NOT_RUNNING: 'DAEMON_NOT_RUNNING',
|
||||
INSTANCE_NOT_FOUND: 'INSTANCE_NOT_FOUND',
|
||||
PLUGIN_NOT_FOUND: 'PLUGIN_NOT_FOUND',
|
||||
AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',
|
||||
CONFIG_INVALID: 'CONFIG_INVALID',
|
||||
CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',
|
||||
SETUP_FAILED: 'SETUP_FAILED',
|
||||
API_ERROR: 'API_ERROR',
|
||||
TUNNEL_ERROR: 'TUNNEL_ERROR',
|
||||
INSTALL_FAILED: 'INSTALL_FAILED',
|
||||
UNINSTALL_FAILED: 'UNINSTALL_FAILED',
|
||||
MISSING_ARGUMENT: 'MISSING_ARGUMENT',
|
||||
UNKNOWN_COMMAND: 'UNKNOWN_COMMAND',
|
||||
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
|
||||
} as const;
|
||||
```
|
||||
|
||||
New codes may be added as needed during implementation.
|
||||
|
||||
## Noise Handling
|
||||
|
||||
| Source | Stream | Solution |
|
||||
|--------|--------|----------|
|
||||
| Pino logger | stderr | Call `muteForJson()` at command start to suppress |
|
||||
| `console.log` in commands | stdout | `jsonSuccess`/`jsonError` call `process.exit()`, so subsequent logs never execute |
|
||||
| Progress bars (`process.stdout.write`) | stdout | Guard with `if (!json)` or place after `jsonSuccess` call |
|
||||
| Spinners (ora) | stdout | Not used in CLI commands currently; guard if added |
|
||||
|
||||
### Command Pattern
|
||||
|
||||
```typescript
|
||||
export async function cmdExample(args: string[], instanceRoot?: string): Promise<void> {
|
||||
const json = isJsonMode(args);
|
||||
if (json) muteForJson();
|
||||
|
||||
try {
|
||||
// ... command logic ...
|
||||
|
||||
if (json) jsonSuccess(data); // exits, nothing below runs
|
||||
|
||||
// Human-readable output
|
||||
console.log('...');
|
||||
} catch (err) {
|
||||
if (json) jsonError(ErrorCodes.SOME_ERROR, err.message); // exits
|
||||
console.error('...');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Commands In Scope
|
||||
|
||||
### Group A — Data/Query Commands
|
||||
|
||||
| Command | `data` shape |
|
||||
|---------|-------------|
|
||||
| `agents list` | `{ agents: [{ key, name, version, distribution, description, installed, available, missingDeps }] }` |
|
||||
| `agents info <key>` | `{ key, name, version, distribution, description, installed, binaryPath?, command?, registryId? }` |
|
||||
| `plugins` / `plugin list` | `{ plugins: [{ name, version, enabled, source, description }] }` |
|
||||
| `plugin search <q>` | `{ results: [{ name, version, description }] }` |
|
||||
| `status` | `{ instances: [{ id, name, status, pid, dir, mode, channels, apiPort, tunnelPort }] }` |
|
||||
| `status --id <id>` | `{ id, name, status, pid, dir, mode, channels, apiPort, tunnelPort }` |
|
||||
| `config set <k> <v>` | `{ path, value, needsRestart }` |
|
||||
| `doctor --json` | `{ categories: [{ name, results: [{ status, message }] }], summary: { passed, warnings, failed } }` |
|
||||
| `tunnel list` | `{ tunnels: [{ port, label?, publicUrl?, status }] }` |
|
||||
| `api *` (20+ subcommands) | Normalized wrap of API response |
|
||||
| `version` | `{ version: "2026.401.1" }` |
|
||||
|
||||
Notes:
|
||||
- `config` (no args) opens interactive editor — not JSON-compatible. Only `config set` supports `--json`.
|
||||
- `doctor --json` implies `--dry-run` (no interactive fix prompts). Reports checks only. Always exits 0 with `success: true` — caller checks `summary.failed` to determine health.
|
||||
|
||||
### Group B — Action/Result Commands
|
||||
|
||||
| Command | `data` shape |
|
||||
|---------|-------------|
|
||||
| `start` | `{ pid, instanceId, dir }` |
|
||||
| `stop` | `{ stopped: true, pid }` |
|
||||
| `restart` | `{ pid, instanceId, dir }` |
|
||||
| `install <plugin>` | `{ plugin, version, installed: true }` |
|
||||
| `uninstall <plugin>` | `{ plugin, uninstalled: true }` |
|
||||
| `agents install <key>` | `{ key, version, installed: true }` |
|
||||
| `agents uninstall <key>` | `{ key, uninstalled: true }` |
|
||||
| `setup` | `{ configPath }` |
|
||||
| `adopt` | `{ sessionId, threadId, agent, status }` |
|
||||
| `remote` | `{ code, name, role, expiresAt, urls: { local, tunnel?, app? } }` |
|
||||
| `tunnel add` | `{ port, publicUrl }` |
|
||||
| `tunnel stop` | `{ port, stopped: true }` |
|
||||
| `tunnel stop-all` | `{ stopped: true }` |
|
||||
| `plugin enable/disable` | `{ plugin, enabled: boolean }` |
|
||||
|
||||
Notes:
|
||||
- `restart --foreground` starts a blocking server — incompatible with `--json`. When `--json` is passed, `restart` always uses daemon mode regardless of config.
|
||||
- `plugin configure` and `plugin create` are interactive — not JSON-compatible.
|
||||
|
||||
### Out of Scope
|
||||
|
||||
`logs`, `attach`, `onboard`, `reset`, `dev`, `help`, `default`, `config` (interactive editor), `plugin configure`, `plugin create`, `agents run` — these are interactive, streaming, or blocking commands where JSON output is not applicable.
|
||||
|
||||
## Help Text
|
||||
|
||||
Commands that support `--json` must document it in their `--help` output. Add a line like:
|
||||
|
||||
```
|
||||
--json Output result as JSON
|
||||
```
|
||||
|
||||
## Migration: Existing `--json` Commands
|
||||
|
||||
Two commands already support `--json` with non-standard formats. Both will be migrated to the new envelope format.
|
||||
|
||||
**`agents list --json`** (breaking change):
|
||||
- Before: `[{ key, name, ... }]` (raw array)
|
||||
- After: `{ "success": true, "data": { "agents": [{ key, name, ... }] } }`
|
||||
|
||||
**`setup --json`** (breaking change):
|
||||
- Before: `{ success: false, error: "string" }` / `{ success: true, configPath }`
|
||||
- After: `{ "success": false, "error": { "code": "SETUP_FAILED", "message": "..." } }` / `{ "success": true, "data": { "configPath": "..." } }`
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Layer 1: Unit Tests — `output.ts` helpers
|
||||
|
||||
File: `src/cli/commands/__tests__/output.test.ts`
|
||||
|
||||
- `isJsonMode()` returns correct boolean for various arg combinations
|
||||
- `jsonSuccess()` outputs valid single-line JSON with `{ success: true, data }` and exits 0
|
||||
- `jsonError()` outputs valid single-line JSON with `{ success: false, error: { code, message } }` and exits non-zero
|
||||
- `muteForJson()` calls `muteLogger()`
|
||||
- All `ErrorCodes` values are unique strings
|
||||
|
||||
### Layer 2: Integration Tests — per-command JSON output
|
||||
|
||||
File: `src/cli/commands/__tests__/json-output.test.ts`
|
||||
|
||||
For each command with `--json` support:
|
||||
|
||||
1. **Success case**: mock dependencies, call with `--json`, verify:
|
||||
- Output is valid JSON (parseable by `JSON.parse`)
|
||||
- `success === true`
|
||||
- `data` matches expected shape
|
||||
- Exit code 0
|
||||
2. **Error case**: trigger error condition, verify:
|
||||
- Output is valid JSON (not ANSI text or stack trace)
|
||||
- `success === false`
|
||||
- `error.code` is a known error code string
|
||||
- `error.message` is a non-empty string
|
||||
- Exit code non-zero
|
||||
3. **No noise**: stdout contains exactly one line of JSON, no progress bars, ANSI codes, or extraneous text
|
||||
|
||||
### Layer 3: Contract Tests — JSON schema stability
|
||||
|
||||
File: `src/cli/commands/__tests__/json-contract.test.ts`
|
||||
|
||||
Snapshot-style tests that verify the shape of `data` for each command does not change unexpectedly. These protect consumers from silent breaking changes.
|
||||
|
||||
```typescript
|
||||
it('agents list --json contract', () => {
|
||||
const output = JSON.parse(stdout);
|
||||
expect(output).toHaveProperty('success', true);
|
||||
expect(output).toHaveProperty('data.agents');
|
||||
expect(output.data.agents[0]).toMatchObject({
|
||||
key: expect.any(String),
|
||||
name: expect.any(String),
|
||||
installed: expect.any(Boolean),
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Test Helpers
|
||||
|
||||
Shared utilities in `src/cli/commands/__tests__/helpers/json-test-utils.ts`:
|
||||
|
||||
```typescript
|
||||
function captureJsonOutput(fn: () => Promise<void>): { stdout: string; exitCode: number };
|
||||
function expectValidJsonSuccess(stdout: string, dataShape?: object): void;
|
||||
function expectValidJsonError(stdout: string, expectedCode?: string): void;
|
||||
```
|
||||
|
||||
### Estimated Test Count
|
||||
|
||||
- ~15-20 tests for output helpers (Layer 1)
|
||||
- ~2-3 tests per command × ~20 commands = ~40-60 tests (Layer 2)
|
||||
- ~1 test per command × ~20 commands = ~20 tests (Layer 3)
|
||||
- Total: ~75-100 test cases
|
||||
@ -0,0 +1,299 @@
|
||||
# Spec: Instances CLI & Auth Codes
|
||||
|
||||
**Date:** 2026-04-02
|
||||
**Status:** Draft
|
||||
**Related specs:**
|
||||
- [Spec 1: API Server Core](./2026-03-31-api-server-core-design.md)
|
||||
- [Spec 2: Auth System](./2026-03-31-auth-system-design.md)
|
||||
- [Spec 4: App Connectivity](./2026-03-31-app-connectivity-design.md)
|
||||
- [Multi-Instance Design](./2026-03-30-multi-instance-design.md)
|
||||
- [App Spec: Add Workspace Feature](../../OpenACP-App/docs/superpowers/specs/2026-04-02-add-workspace-feature-design.md)
|
||||
|
||||
## Overview
|
||||
|
||||
Three additions to the OpenACP core to support the Add Workspace feature in the desktop app:
|
||||
|
||||
1. **`openacp instances` CLI subcommand** — list and create instances with app-friendly JSON output.
|
||||
2. **Extend `start --json` output** — include full instance info after startup (wizard or normal start).
|
||||
3. **Auth code exchange** — one-time codes for secure remote connection, replacing JWT-in-URL.
|
||||
4. **`GET /api/v1/workspace` endpoint** — lets authenticated clients fetch workspace identity info.
|
||||
|
||||
---
|
||||
|
||||
## 1. `openacp instances` CLI Subcommand
|
||||
|
||||
### Relationship to `openacp status --all`
|
||||
|
||||
`openacp status --all` already exists and lists all instances in a table format for terminal users. The new `openacp instances list` command targets **app consumption**: its JSON output uses a different schema (`directory` = parent of `.openacp` root, `root` = `.openacp` path) compared to `status --all --json` which returns runtime fields (`channels`, `runMode`, `pid`). Human-readable output of `instances list` reuses the same table rendering as `status --all`.
|
||||
|
||||
---
|
||||
|
||||
### `openacp instances list`
|
||||
|
||||
Lists all registered instances with live status.
|
||||
|
||||
```
|
||||
openacp instances list [--json]
|
||||
```
|
||||
|
||||
**Status check per instance:**
|
||||
1. Read `<root>/openacp.pid` — file missing → `stopped`
|
||||
2. If PID file exists, check process alive (kill -0) → dead process → `stopped`
|
||||
3. If process alive, `GET http://localhost:<port>/api/v1/system/health` → confirm alive → `running`
|
||||
|
||||
**JSON output (`--json`):**
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "main",
|
||||
"name": "Main",
|
||||
"directory": "/Users/user",
|
||||
"root": "/Users/user/.openacp",
|
||||
"status": "running",
|
||||
"port": 21420
|
||||
},
|
||||
{
|
||||
"id": "my-project",
|
||||
"name": "My Project",
|
||||
"directory": "/Users/user/my-project",
|
||||
"root": "/Users/user/my-project/.openacp",
|
||||
"status": "stopped",
|
||||
"port": null
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
All paths are **absolute** — no `~/` prefix. `directory` = `path.dirname(root)` (the human-facing project folder, not the `.openacp` subdirectory itself).
|
||||
|
||||
**Human-readable output (no `--json`):** Same table format as `openacp status --all`. Can share rendering logic.
|
||||
|
||||
---
|
||||
|
||||
### `openacp instances create`
|
||||
|
||||
Creates or registers a new instance at a given directory, non-interactively.
|
||||
|
||||
```
|
||||
openacp instances create
|
||||
--dir <path> Target directory — system appends /.openacp internally (user-facing convention from multi-instance spec)
|
||||
[--from <path>] Clone from this existing instance directory (same convention: parent dir, not /.openacp)
|
||||
[--name <name>] Instance name (default: openacp-<N>)
|
||||
[--agent <agentName>] Set default agent in config
|
||||
[--no-interactive] Skip setup wizard entirely
|
||||
[--json] Print resulting instance info as JSON to stdout
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
|
||||
```
|
||||
→ Resolve --dir to absolute path (expand ~/, resolve symlinks)
|
||||
→ Check <dir>/.openacp already exists?
|
||||
→ Yes + already in registry:
|
||||
→ Error: "Instance already exists at <dir> (id: <id>)"
|
||||
→ Exit 1
|
||||
→ Yes + not in registry:
|
||||
→ Read instanceName from <dir>/.openacp/config.json
|
||||
→ Register entry in ~/.openacp/instances.json
|
||||
→ Skip creation, go to output step
|
||||
→ No .openacp yet:
|
||||
→ --from <fromPath> provided:
|
||||
→ Validate <fromPath>/.openacp/config.json exists (error if not found)
|
||||
→ Clone using existing copy logic (from multi-instance spec)
|
||||
→ Register new instance in ~/.openacp/instances.json
|
||||
→ --no-interactive (no --from):
|
||||
→ Create <dir>/.openacp/ directory structure
|
||||
→ Write minimal config.json: { instanceName: <name>, runMode: "daemon" }
|
||||
→ Write agents.json with default agent if --agent provided
|
||||
→ Register in ~/.openacp/instances.json
|
||||
→ Output step:
|
||||
→ --json: print instance info JSON to stdout, exit 0
|
||||
→ No --json: print "Instance created: <name> at <dir>", exit 0
|
||||
```
|
||||
|
||||
**JSON output (`--json`):**
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-project",
|
||||
"name": "My Project",
|
||||
"directory": "/Users/user/my-project",
|
||||
"root": "/Users/user/my-project/.openacp",
|
||||
"status": "stopped",
|
||||
"port": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Extend `start --json` and Onboarding Output
|
||||
|
||||
### Current `start --json` Output
|
||||
|
||||
`openacp start --json` (and the default command when starting) already outputs:
|
||||
```json
|
||||
{ "success": true, "data": { "pid": 1234, "instanceId": "main", "dir": "/Users/user/.openacp" } }
|
||||
```
|
||||
|
||||
`dir` here is the `.openacp` root path.
|
||||
|
||||
### Required Change
|
||||
|
||||
Extend the `data` payload to include `name` and `directory` (the parent folder, i.e., the human-facing project folder):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"pid": 1234,
|
||||
"instanceId": "main",
|
||||
"name": "Main",
|
||||
"directory": "/Users/user",
|
||||
"dir": "/Users/user/.openacp",
|
||||
"port": 21420
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`dir` is kept for backward compatibility. `directory` is `path.dirname(dir)`.
|
||||
|
||||
### Onboarding Wizard with `--json`
|
||||
|
||||
When `openacp` (or `openacp start`) is run with `--json` and no config exists:
|
||||
|
||||
1. The setup wizard runs normally (interactive terminal prompts — `--json` controls output format, not interactivity).
|
||||
2. After wizard completes and server starts, the extended `start --json` output is emitted.
|
||||
|
||||
The app reads this JSON from sidecar stdout to capture the newly created instance's `id` immediately after setup completes.
|
||||
|
||||
---
|
||||
|
||||
## 3. Auth Code Exchange
|
||||
|
||||
### Motivation
|
||||
|
||||
The current `openacp remote` spec embeds the JWT directly in the URL (`?token=eyJ...`). Tokens in URLs can be logged by proxies, cached by browsers, and exposed in QR codes. Replacing the JWT with a short-lived one-time code means the actual token is never exposed in a URL.
|
||||
|
||||
### New Endpoints
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| `POST` | `/api/v1/auth/codes` | Secret token only | Generate one-time code |
|
||||
| `POST` | `/api/v1/auth/exchange` | None (code is credential) | Exchange code for JWT |
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/auth/codes`
|
||||
|
||||
Only callable with secret token auth.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"role": "admin",
|
||||
"name": "remote-14h30-31-03-2026",
|
||||
"expire": "24h",
|
||||
"scopes": ["sessions:read"]
|
||||
}
|
||||
```
|
||||
Same fields as `POST /api/v1/auth/tokens` — the code carries the intended token parameters.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"code": "abc123xyz",
|
||||
"expiresAt": "2026-04-02T14:35:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Storage:** In-memory Map `code → { tokenParams, expiresAt, used: false }`. Codes expire after 5 minutes. Cleanup on exchange or expiry.
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/auth/exchange`
|
||||
|
||||
No authentication required — the code is the credential.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{ "code": "abc123xyz" }
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
→ Look up code in store
|
||||
→ Not found: 401 "Invalid code"
|
||||
→ Found but expired: 401 "Code expired"
|
||||
→ Found but already used: 401 "Code already used"
|
||||
→ Mark code as used (single-use, prevent replay)
|
||||
→ Call internal token generation with stored tokenParams
|
||||
→ Return same response as POST /api/v1/auth/tokens
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"accessToken": "eyJ...",
|
||||
"tokenId": "tok_abc123",
|
||||
"expiresAt": "2026-04-03T14:30:00Z",
|
||||
"refreshDeadline": "2026-04-09T14:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `openacp remote` — Updated Link Format
|
||||
|
||||
```
|
||||
openacp remote
|
||||
→ POST /api/v1/auth/codes (secret token) → code "abc123xyz"
|
||||
→ Generate links:
|
||||
openacp://connect?host=<tunnel>&code=abc123xyz
|
||||
https://<tunnel>?code=abc123xyz
|
||||
http://localhost:<port>?code=abc123xyz
|
||||
```
|
||||
|
||||
The `token=` query param in all link formats is replaced by `code=`. The auth spec's existing link formats are updated accordingly.
|
||||
|
||||
---
|
||||
|
||||
## 4. `GET /api/v1/workspace`
|
||||
|
||||
Returns identity information about the current workspace/instance. Used by the app after connecting to a remote workspace to retrieve the instance `id` and display info.
|
||||
|
||||
**Auth:** Any valid auth (secret token or JWT — no specific scope required beyond authentication).
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"id": "main",
|
||||
"name": "Main",
|
||||
"directory": "/Users/user",
|
||||
"version": "2026.401.1"
|
||||
}
|
||||
```
|
||||
|
||||
`directory` is `path.dirname(instanceRoot)` — the parent of the `.openacp` folder, i.e., the human-facing project folder.
|
||||
|
||||
`directory` is the server-side filesystem path. For remote workspaces, it is meaningful for display only — connection routing uses `host`, not `directory`.
|
||||
|
||||
---
|
||||
|
||||
## Files to Add / Modify
|
||||
|
||||
### New Files (core)
|
||||
- `src/cli/commands/instances.ts` — `instances list` and `instances create` subcommands
|
||||
- `src/plugins/api-server/routes/workspace.ts` — `GET /api/v1/workspace` route
|
||||
- `src/plugins/api-server/auth/code-store.ts` — in-memory code store (TTL + single-use)
|
||||
- `src/plugins/api-server/routes/auth-codes.ts` — `POST /api/v1/auth/codes` and `POST /api/v1/auth/exchange` routes
|
||||
|
||||
### Modified Files (core)
|
||||
- `src/cli.ts` — register `instances` subcommand in instance-aware command map
|
||||
- `src/cli/commands/index.ts` — export `cmdInstances`
|
||||
- `src/cli/commands/start.ts` — extend `--json` output with `name`, `directory`, `port`
|
||||
- `src/cli/commands/default.ts` — extend `--json` output (startup after wizard) with same fields
|
||||
- `src/plugins/api-server/routes/auth.ts` — register new code exchange routes
|
||||
- `src/plugins/api-server/server.ts` — register workspace route
|
||||
|
||||
### Modified Files (app)
|
||||
See companion spec: [App Spec: Add Workspace Feature](../../OpenACP-App/docs/superpowers/specs/2026-04-02-add-workspace-feature-design.md)
|
||||
325
docs/superpowers/specs/2026-04-02-menu-button-fix-design.md
Normal file
325
docs/superpowers/specs/2026-04-02-menu-button-fix-design.md
Normal file
@ -0,0 +1,325 @@
|
||||
# Menu & Command Dispatch Fix
|
||||
|
||||
**Date:** 2026-04-02
|
||||
**Status:** Draft
|
||||
**Scope:** Fix broken menu buttons, fix slash commands dispatching to generic core handlers, add button-driven New Session flow
|
||||
|
||||
## Problem
|
||||
|
||||
The main menu shows 10 buttons. When pressed, the `m:` callback handler dispatches them through `CommandRegistry` (core, generic handlers) or does nothing (`callback` type). This causes:
|
||||
|
||||
1. **3 buttons completely broken**: Settings (`callback` type → `break`), Update (placeholder text), Doctor (placeholder text)
|
||||
2. **3 buttons with degraded UX**: Sessions (loses cleanup buttons, status emoji), Agents (loses pagination, install buttons), Help (generic text instead of rich formatted)
|
||||
3. **1 button unnecessarily slow**: New Session delegates everything to AI when most steps could use buttons
|
||||
4. **1 button unreliable**: Restart uses `setTimeout` from callback context
|
||||
5. **Slash commands have the same problems**: `/agents`, `/sessions`, `/doctor`, `/update`, `/help`, `/restart` all go through core generic handlers, missing Telegram-specific rich UI
|
||||
6. **1 orphaned callback**: `m:topics` (Refresh button in sessions list) has no handler
|
||||
|
||||
Buttons that work correctly: Status, Integrate, and all inner buttons (cleanup, agent install, settings toggle/select, switch, permissions, TTS).
|
||||
|
||||
## Design
|
||||
|
||||
### Principle
|
||||
|
||||
Two layers of command handling already exist:
|
||||
- **Core handlers** in `CommandRegistry` — platform-agnostic, return `CommandResponse`
|
||||
- **Telegram handlers** — rich UI with inline keyboards, pagination, progress updates
|
||||
|
||||
The problem is that the `m:` menu handler and the slash command dispatcher both route to core handlers exclusively. The fix: register Telegram adapter overrides in `CommandRegistry` so both paths (menu button + slash command) get rich UI.
|
||||
|
||||
### Part 1: Telegram Command Overrides via Intercept Map
|
||||
|
||||
`CommandRegistry` supports adapter-scoped overrides, but override handlers receive `CommandArgs` — not grammY `Context`. The Telegram handlers (`handleAgents`, `handleDoctor`, etc.) need grammY `Context` for inline keyboards, message editing, and rich UI.
|
||||
|
||||
Instead of bridging `CommandArgs` → `Context`, use an intercept map: a lookup table that maps command names to Telegram handler functions. Both the slash command dispatcher and the `m:` menu handler check this map before falling through to `CommandRegistry`.
|
||||
|
||||
Commands intercepted:
|
||||
|
||||
| Command | Telegram handler | What it does |
|
||||
|---------|-----------------|-------------|
|
||||
| `/agents` | `handleAgents(ctx, core)` | Paginated list + install buttons |
|
||||
| `/sessions` | `handleTopics(ctx, core)` | Status emoji + cleanup buttons + refresh |
|
||||
| `/doctor` | `handleDoctor(ctx)` | Run diagnostics + show report + fix buttons |
|
||||
| `/update` | `handleUpdate(ctx, core)` | Version check + download + restart |
|
||||
| `/restart` | `handleRestart(ctx, core)` | Send message, wait for delivery, then restart |
|
||||
| `/help` | `handleHelp(ctx)` | Rich formatted help with sections |
|
||||
|
||||
Implementation:
|
||||
|
||||
```typescript
|
||||
// Shared intercept map — used by both slash command handler and m: menu handler
|
||||
const TELEGRAM_OVERRIDES: Record<string, (ctx: Context, core: OpenACPCore) => Promise<void>> = {
|
||||
agents: (ctx, core) => handleAgents(ctx, core),
|
||||
sessions: (ctx, core) => handleTopics(ctx, core),
|
||||
doctor: (ctx, _core) => handleDoctor(ctx),
|
||||
update: (ctx, core) => handleUpdate(ctx, core),
|
||||
restart: (ctx, core) => handleRestart(ctx, core),
|
||||
help: (ctx, _core) => handleHelp(ctx),
|
||||
}
|
||||
```
|
||||
|
||||
#### Slash command dispatch change
|
||||
|
||||
In the `bot.on("message:text")` handler at adapter.ts:322, check the intercept map before `registry.execute()`:
|
||||
|
||||
```typescript
|
||||
// Before: always calls registry.execute()
|
||||
// After: check intercept map first
|
||||
const override = TELEGRAM_OVERRIDES[commandName]
|
||||
if (override) {
|
||||
await override(ctx, core)
|
||||
return // don't fall through to registry.execute()
|
||||
}
|
||||
const response = await registry.execute(text, { ... })
|
||||
```
|
||||
|
||||
#### Menu `m:` handler change for `command` type
|
||||
|
||||
In the `m:` handler's `command` case in `commands/index.ts`, check the intercept map before `registry.execute()`:
|
||||
|
||||
```typescript
|
||||
case 'command': {
|
||||
const cmdName = item.action.command.replace(/^\//, '').split(' ')[0]
|
||||
const override = TELEGRAM_OVERRIDES[cmdName]
|
||||
if (override) {
|
||||
await override(ctx, core)
|
||||
break
|
||||
}
|
||||
// Fallback: dispatch through CommandRegistry (for commands without overrides)
|
||||
const response = await registry.execute(item.action.command, { ... })
|
||||
// ... render response
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
The intercept map is defined once and shared between both dispatch paths. Core handlers remain as fallback for non-Telegram channels.
|
||||
|
||||
### Part 2: Fix `callback` Type in `m:` Handler
|
||||
|
||||
The `m:` handler has `case 'callback': break;` which silently does nothing. This breaks the Settings button (`s:settings` callbackData).
|
||||
|
||||
The issue: grammY callback routing already matched `m:core:settings` → the broad `m:` handler consumed it. The `s:settings` callback data is never re-dispatched to `setupSettingsCallbacks`.
|
||||
|
||||
Fix: handle known callback data directly in the `callback` case. grammY does not support re-dispatching callback data, so we must call handlers directly.
|
||||
|
||||
```typescript
|
||||
case 'callback': {
|
||||
const cbData = item.action.callbackData
|
||||
if (cbData === 's:settings') {
|
||||
await handleSettings(ctx, core)
|
||||
} else if (cbData.startsWith('ns:')) {
|
||||
// New Session flow — call showAgentPicker directly
|
||||
await showAgentPicker(ctx, core, chatId)
|
||||
}
|
||||
// Future callback types can be added here
|
||||
break
|
||||
}
|
||||
```
|
||||
|
||||
This handles the two known `callback` actions: Settings (`s:settings`) and New Session (`ns:start`). Plugins adding new `callback` menu items would need to extend this case — but that's a rare scenario. A more general solution (callback registry) can be added later if needed.
|
||||
|
||||
### Part 3: New Session Button Flow
|
||||
|
||||
Replace the current `delegate` action (sends everything to AI) with a multi-step button flow. AI is only involved when the user needs to type a custom workspace path.
|
||||
|
||||
#### Flow
|
||||
|
||||
```
|
||||
[🆕 New Session] (callback: ns:start)
|
||||
↓
|
||||
📋 Select agent (inline buttons)
|
||||
[claude-code] [gemini]
|
||||
[codex] [goose]
|
||||
↓ user taps agent
|
||||
📁 Select workspace (inline buttons)
|
||||
[~/project-a] ← from recent session history
|
||||
[~/project-b] ← from recent session history
|
||||
[📁 Custom path...] ← only this goes to AI
|
||||
↓
|
||||
If recent workspace selected:
|
||||
→ createSessionDirect(agent, workspace) — no AI needed
|
||||
If "Custom path..." selected:
|
||||
→ delegate to AI: "User wants session with agent X, ask for workspace path"
|
||||
```
|
||||
|
||||
#### Callback prefix: `ns:`
|
||||
|
||||
| Callback data | Action |
|
||||
|--------------|--------|
|
||||
| `ns:start` | Show agent picker |
|
||||
| `ns:agent:{agentKey}` | Show workspace picker for this agent |
|
||||
| `ns:ws:{id}` | Create session directly (workspace resolved from cache) |
|
||||
| `ns:custom:{agentKey}` | Delegate to AI for workspace input |
|
||||
|
||||
#### Callback data size constraint
|
||||
|
||||
Telegram limits callback_data to 64 bytes. Workspace paths can easily exceed this (e.g. `ns:ws:claude-code:/Users/lucas/some-long-path` = 50+ chars). The adapter already has a compression mechanism (`toCallbackData`/`fromCallbackData` with `callbackCache` Map) but it only handles the `c/` prefix.
|
||||
|
||||
For `ns:ws:` callbacks, use a workspace cache instead of embedding the path:
|
||||
|
||||
```typescript
|
||||
// Store workspace in a short-lived cache keyed by numeric ID
|
||||
const workspaceCache = new Map<number, { agentKey: string; workspace: string }>()
|
||||
let nextWsId = 0
|
||||
|
||||
// When building workspace picker buttons:
|
||||
const id = nextWsId++
|
||||
workspaceCache.set(id, { agentKey, workspace })
|
||||
kb.text(shortLabel, `ns:ws:${id}`) // always short callback data
|
||||
|
||||
// When handling ns:ws callback:
|
||||
const entry = workspaceCache.get(id)
|
||||
if (!entry) { /* expired — show picker again */ }
|
||||
```
|
||||
|
||||
This keeps callback data under 20 bytes regardless of path length.
|
||||
|
||||
#### Agent picker
|
||||
|
||||
Shows installed agents as inline buttons (max 2 per row). Source: `core.agentCatalog.getAvailable().filter(i => i.installed)`.
|
||||
|
||||
If only 1 agent installed → skip agent picker, go directly to workspace picker.
|
||||
|
||||
#### Workspace picker
|
||||
|
||||
Recent workspaces extracted from session records:
|
||||
|
||||
```typescript
|
||||
const records = core.sessionManager.listRecords()
|
||||
const workspaces = [...new Set(records.map(r => r.workingDir))]
|
||||
.slice(0, 5) // max 5 recent workspaces
|
||||
```
|
||||
|
||||
Each workspace shown as a button. Plus "📁 Custom path..." at the bottom.
|
||||
|
||||
If no recent workspaces → use config `workspace.baseDir` as the only option + Custom.
|
||||
|
||||
#### Registration
|
||||
|
||||
New function `setupNewSessionCallbacks(bot, core, chatId)` in `commands/new-session.ts`, called from `setupAllCallbacks()` before the broad `m:` handler.
|
||||
|
||||
### Part 4: Fix `m:topics` Refresh Button
|
||||
|
||||
The sessions list (`handleTopics`) creates a "Refresh" button with callback `m:topics`. This reaches the broad `m:` handler which looks up `menuRegistry.getItem("topics")` → undefined → nothing happens.
|
||||
|
||||
Fix: add explicit handling in the `m:` handler for `m:topics`:
|
||||
|
||||
```typescript
|
||||
// In the broad m: handler, before menuRegistry lookup
|
||||
if (itemId === 'topics') {
|
||||
await handleTopics(ctx, core)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, register `m:topics` as a specific callback handler in `setupSessionCallbacks()` (before the broad handler), which is cleaner.
|
||||
|
||||
### Part 5: Core Menu Items Update
|
||||
|
||||
Changes to `src/core/menu/core-items.ts`:
|
||||
|
||||
| Item | Current action | New action | Reason |
|
||||
|------|---------------|------------|--------|
|
||||
| New Session | `delegate` | `callback: ns:start` | Button flow instead of AI |
|
||||
| Restart | `command: /restart` | `command: /restart` | No change — override handles rich UI |
|
||||
| Update | `command: /update` | `command: /update` | No change — override handles rich UI |
|
||||
|
||||
All other items keep their current action type — the adapter overrides handle the rich UI transparently.
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change | ~LOC |
|
||||
|------|--------|------|
|
||||
| `src/plugins/telegram/adapter.ts` | Add `TELEGRAM_OVERRIDES` map, intercept in slash command handler | +20 |
|
||||
| `src/plugins/telegram/commands/index.ts` | Fix `callback` case, intercept in `m:` handler `command` case, add `m:topics` handling | +30 |
|
||||
| `src/plugins/telegram/commands/new-session.ts` | Add `setupNewSessionCallbacks()` with `ns:` prefix handlers | +80 |
|
||||
| `src/core/menu/core-items.ts` | Change New Session action to `callback: ns:start` | ~2 |
|
||||
| `src/plugins/telegram/commands/session.ts` | Add `m:topics` specific callback (before broad handler) | ~5 |
|
||||
|
||||
No files deleted. No core type changes. No breaking changes.
|
||||
|
||||
## Complete Flow Diagrams
|
||||
|
||||
### Flow 1: User taps "🆕 New Session" menu button
|
||||
|
||||
```
|
||||
User taps [🆕 New Session]
|
||||
→ callback_data = "m:core:new"
|
||||
→ broad m: handler → menuRegistry.getItem("core:new")
|
||||
→ action.type === 'callback', callbackData: 'ns:start'
|
||||
→ case 'callback': cbData starts with 'ns:' → call setupNewSessionCallbacks handler directly
|
||||
→ shows agent picker buttons (edit existing message)
|
||||
→ user taps [claude-code] → ns:agent:claude-code
|
||||
→ ns: handler shows workspace picker: [~/project-a] [~/project-b] [📁 Custom...]
|
||||
→ user taps [~/project-a] → ns:ws:42
|
||||
→ ns: handler resolves workspace from cache → createSessionDirect(ctx, core, chatId, "claude-code", "~/project-a")
|
||||
→ ✅ Session created with topic
|
||||
```
|
||||
|
||||
Note: The callback_data `m:core:new` is consumed by the broad `m:` handler. Inside `case 'callback'`, the handler must call the `ns:` logic directly — it cannot re-dispatch `ns:start` as a new callback because grammY doesn't support that. Implementation: extract the agent picker logic into a standalone function `showAgentPicker(ctx, core, chatId)` and call it from both the `m:` handler's callback case and the `ns:start` callback handler.
|
||||
|
||||
### Flow 2: User taps "🤖 Agents" menu button
|
||||
|
||||
```
|
||||
User taps [🤖 Agents]
|
||||
→ callback_data = "m:core:agents"
|
||||
→ broad m: handler → action.type === 'command', command: '/agents'
|
||||
→ intercept map check: TELEGRAM_OVERRIDES['agents'] exists
|
||||
→ calls handleAgents(ctx, core)
|
||||
→ shows paginated agent list with install buttons
|
||||
```
|
||||
|
||||
### Flow 3: User types "/doctor" as slash command
|
||||
|
||||
```
|
||||
User types "/doctor"
|
||||
→ bot.on("message:text") → commandName = "doctor"
|
||||
→ intercept map check: TELEGRAM_OVERRIDES['doctor'] exists
|
||||
→ calls handleDoctor(ctx)
|
||||
→ shows "Running diagnostics..." → edits message with report + fix buttons
|
||||
→ (registry.execute() never called)
|
||||
```
|
||||
|
||||
### Flow 4: User taps "⚙️ Settings" menu button
|
||||
|
||||
```
|
||||
User taps [⚙️ Settings]
|
||||
→ callback_data = "m:core:settings"
|
||||
→ broad m: handler → action.type === 'callback', callbackData: 's:settings'
|
||||
→ case 'callback': cbData === 's:settings' → handleSettings(ctx, core)
|
||||
→ shows settings keyboard with toggle/select buttons
|
||||
```
|
||||
|
||||
### Flow 5: User taps "Refresh" in sessions list
|
||||
|
||||
```
|
||||
User taps [Refresh]
|
||||
→ callback_data = "m:topics"
|
||||
→ setupSessionCallbacks handler (registered before broad m: handler)
|
||||
→ handleTopics(ctx, core)
|
||||
→ refreshed sessions list with cleanup buttons
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
|
||||
| Case | Behavior |
|
||||
|------|----------|
|
||||
| Only 1 agent installed | New Session skips agent picker, goes to workspace picker |
|
||||
| No recent workspaces | Shows config baseDir + Custom only |
|
||||
| No agents installed | New Session shows "No agents installed. Use /install" |
|
||||
| Intercept handler throws | Caught by existing try/catch in slash command handler and `m:` handler |
|
||||
| User taps old menu button (before update) | `m:core:new` with old `delegate` action — still works via fallback in `m:` handler |
|
||||
| Workspace path is very long | Workspace stored in cache with numeric ID — callback data always under 20 bytes |
|
||||
| Workspace cache entry expired (user waited too long) | Show agent picker again with message "Session expired, please try again" |
|
||||
| Agent key not found after selection | `createSessionDirect` error handling shows error message |
|
||||
|
||||
## Testing
|
||||
|
||||
1. **Menu button dispatch**: Test each of 10 menu buttons produces correct response (not generic text)
|
||||
2. **Slash command dispatch**: Test `/agents`, `/sessions`, `/doctor`, `/update`, `/restart`, `/help` produce rich responses
|
||||
3. **New Session flow**: Test full flow: start → agent picker → workspace picker → session created
|
||||
4. **New Session single agent**: Test auto-skip when only 1 agent installed
|
||||
5. **New Session custom workspace**: Test delegation to AI when "Custom" selected
|
||||
6. **Settings button**: Test `m:core:settings` → settings keyboard appears
|
||||
7. **Refresh button**: Test `m:topics` → sessions list refreshed
|
||||
8. **Intercept map**: Test that intercepted commands skip `registry.execute()`, non-intercepted commands still fall through to core handlers
|
||||
@ -0,0 +1,324 @@
|
||||
# OpenACP Managed Tunnel — Design Spec
|
||||
|
||||
**Date:** 2026-04-02
|
||||
**Status:** Draft
|
||||
|
||||
## Problem
|
||||
|
||||
The current Cloudflare tunnel provider uses unauthenticated quick tunnels
|
||||
(`cloudflared tunnel --url http://localhost:<port>`), which are rate-limited by
|
||||
Cloudflare and produce random `*.trycloudflare.com` URLs. Users have no stable
|
||||
URL and can be throttled without warning.
|
||||
|
||||
## Solution
|
||||
|
||||
Introduce an `openacp` tunnel provider that provisions named Cloudflare tunnels
|
||||
via an OpenACP-owned Cloudflare Worker. Users get stable subdomains under
|
||||
`tunnel.openacp.ai`, no login required, and no rate limits from unauthenticated
|
||||
quick tunnels. The Worker becomes the new default tunnel provider shipped with
|
||||
OpenACP.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
[OpenACP CLI]
|
||||
│
|
||||
├─ POST /tunnel/create (shared API key, IP rate-limited)
|
||||
│
|
||||
[Cloudflare Worker — tunnel-worker.openacp.ai]
|
||||
│
|
||||
├─ Cloudflare API: create named tunnel + DNS record
|
||||
├─ KV: store { tunnelId, dnsName, lastPing } with TTL
|
||||
└─ Returns: { tunnelId, token, publicUrl }
|
||||
│
|
||||
[OpenACP CLI]
|
||||
└─ cloudflared tunnel run --token <token>
|
||||
Traffic: localhost → cloudflared → CF network → abc123.tunnel.openacp.ai
|
||||
|
||||
[Heartbeat — every 10 min]
|
||||
└─ POST /tunnel/:id/ping → Worker resets KV TTL to 24h
|
||||
|
||||
[Cron — every 10 min]
|
||||
└─ Worker scans KV, deletes tunnels with lastPing > 24h ago
|
||||
|
||||
[On stop]
|
||||
└─ DELETE /tunnel/:id → Worker deletes DNS record + tunnel via CF API
|
||||
```
|
||||
|
||||
Two deliverables:
|
||||
- `openacp-tunnel-worker/` — new Cloudflare Worker project (TypeScript + Hono)
|
||||
- `OpenACP/src/plugins/tunnel/providers/openacp.ts` — new `TunnelProvider` implementation
|
||||
|
||||
---
|
||||
|
||||
## Cloudflare Worker
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
openacp-tunnel-worker/
|
||||
src/
|
||||
index.ts — Hono app, route registration
|
||||
routes/
|
||||
create.ts — POST /tunnel/create
|
||||
ping.ts — POST /tunnel/:id/ping
|
||||
destroy.ts — DELETE /tunnel/:id
|
||||
lib/
|
||||
cloudflare-api.ts — Cloudflare REST API calls (create tunnel, DNS, delete)
|
||||
rate-limit.ts — IP rate limiting via KV
|
||||
subdomain.ts — Random 8-char hex subdomain generator
|
||||
cron.ts — Scheduled cleanup handler
|
||||
wrangler.toml
|
||||
```
|
||||
|
||||
### Endpoints
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|----------|---------------------|-------------|-------------------------------------|
|
||||
| `POST` | `/tunnel/create` | Shared key | Provision new ephemeral tunnel |
|
||||
| `POST` | `/tunnel/:id/ping` | Shared key | Reset TTL (heartbeat) |
|
||||
| `DELETE` | `/tunnel/:id` | Shared key | Delete tunnel immediately |
|
||||
| `GET` | `/health` | None | Health check |
|
||||
|
||||
**Authentication:** `Authorization: Bearer <OPENACP_API_KEY>` header on all
|
||||
protected endpoints. Key is an environment secret in `wrangler.toml`.
|
||||
|
||||
### POST /tunnel/create — Response
|
||||
|
||||
```json
|
||||
{
|
||||
"tunnelId": "cf-uuid-...",
|
||||
"publicUrl": "https://abc123.tunnel.openacp.ai",
|
||||
"token": "eyJ..."
|
||||
}
|
||||
```
|
||||
|
||||
### KV Data Model
|
||||
|
||||
**Namespace:** `TUNNELS`
|
||||
**Key:** `tunnel:<tunnelId>`
|
||||
|
||||
```json
|
||||
{
|
||||
"tunnelId": "cf-uuid-...",
|
||||
"dnsName": "abc123.tunnel.openacp.ai",
|
||||
"createdAt": 1743580800,
|
||||
"lastPing": 1743584400
|
||||
}
|
||||
```
|
||||
|
||||
TTL is managed manually via `lastPing`. The cron handler deletes any entry
|
||||
where `lastPing` is more than 24 hours ago, then calls the Cloudflare API to
|
||||
delete the tunnel and its DNS record.
|
||||
|
||||
### IP Rate Limiting
|
||||
|
||||
**Key:** `ratelimit:<ip>`
|
||||
**Value:** request count for the current 1-hour window
|
||||
**Limit:** 5 tunnel creates per IP per hour
|
||||
|
||||
Enforced on `POST /tunnel/create` only.
|
||||
|
||||
### Subdomain Generation
|
||||
|
||||
Generate a random 8-character lowercase hex string. Before creating the DNS
|
||||
record, verify the subdomain is not already in use in KV. Retry up to 3 times
|
||||
on collision (statistically negligible).
|
||||
|
||||
### Cron Schedule
|
||||
|
||||
Runs every 10 minutes. Scans all `tunnel:*` keys in KV. For each entry where
|
||||
`now - lastPing > 86400s` (24h):
|
||||
1. Call CF API: delete DNS record
|
||||
2. Call CF API: delete tunnel
|
||||
3. Delete KV entry
|
||||
|
||||
### Environment Variables (wrangler.toml secrets)
|
||||
|
||||
| Variable | Description |
|
||||
|-----------------------|--------------------------------------------|
|
||||
| `CF_API_TOKEN` | Cloudflare API token with Tunnel + DNS permissions |
|
||||
| `CF_ACCOUNT_ID` | Cloudflare account ID |
|
||||
| `CF_ZONE_ID` | Zone ID for `openacp.ai` |
|
||||
| `OPENACP_API_KEY` | Shared secret checked on all requests |
|
||||
|
||||
---
|
||||
|
||||
## OpenACP Core — `OpenACPTunnelProvider`
|
||||
|
||||
### New File
|
||||
|
||||
`src/plugins/tunnel/providers/openacp.ts`
|
||||
|
||||
Implements the existing `TunnelProvider` interface unchanged.
|
||||
|
||||
### Constructor
|
||||
|
||||
```ts
|
||||
class OpenACPTunnelProvider implements TunnelProvider {
|
||||
constructor(
|
||||
options: Record<string, unknown>,
|
||||
binDir: string,
|
||||
storage: PluginStorage,
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`options` may carry override values for `workerUrl` and `apiKey` (for testing).
|
||||
Default values are constants baked into the binary:
|
||||
|
||||
```ts
|
||||
const DEFAULT_WORKER_URL = 'https://tunnel-worker.openacp.ai'
|
||||
const DEFAULT_API_KEY = '<hardcoded — rotatable via CLI release>'
|
||||
```
|
||||
|
||||
### Persisted State
|
||||
|
||||
State is stored in the tunnel plugin's `ctx.storage` under the key
|
||||
`'openacp-tunnels'`, as a `Record<string, TunnelState>` keyed by port number
|
||||
(string form, since JSON keys are strings):
|
||||
|
||||
```ts
|
||||
interface TunnelState {
|
||||
tunnelId: string
|
||||
token: string
|
||||
publicUrl: string
|
||||
}
|
||||
|
||||
// Example value in storage:
|
||||
// {
|
||||
// "3100": { tunnelId: "cf-...", token: "eyJ...", publicUrl: "https://abc.tunnel.openacp.ai" },
|
||||
// "5173": { tunnelId: "cf-...", token: "eyJ...", publicUrl: "https://xyz.tunnel.openacp.ai" }
|
||||
// }
|
||||
```
|
||||
|
||||
### start(port) Flow
|
||||
|
||||
```
|
||||
1. Load all = storage.get('openacp-tunnels') ?? {}
|
||||
2. If all[port] exists:
|
||||
a. POST /tunnel/<tunnelId>/ping
|
||||
b. If 200 OK → reuse: token = all[port].token, publicUrl = all[port].publicUrl
|
||||
c. If error (404/network) → delete all[port], proceed to step 3
|
||||
3. POST /tunnel/create → { tunnelId, token, publicUrl }
|
||||
a. all[port] = { tunnelId, token, publicUrl }
|
||||
b. storage.set('openacp-tunnels', all)
|
||||
4. spawn cloudflared tunnel run --token <token>
|
||||
(publicUrl is already known from Worker response — no stdout parsing needed.
|
||||
If process exits within 10s, treat as failure and throw.)
|
||||
5. Start heartbeat: setInterval(() => pingWorker(tunnelId), 10 * 60 * 1000)
|
||||
6. Return publicUrl
|
||||
```
|
||||
|
||||
### stop(force?) Flow
|
||||
|
||||
```
|
||||
1. clearInterval(heartbeat)
|
||||
2. Kill cloudflared process (SIGTERM → SIGKILL after 5s, or SIGKILL immediately if force)
|
||||
3. DELETE /tunnel/<tunnelId> (fire-and-forget, log error if fails)
|
||||
4. Load all = storage.get('openacp-tunnels') ?? {}
|
||||
delete all[port]
|
||||
storage.set('openacp-tunnels', all)
|
||||
```
|
||||
|
||||
### Crash / Unexpected Exit (onExit)
|
||||
|
||||
When cloudflared exits after establishment:
|
||||
- Do NOT call DELETE (tunnel is still valid on CF)
|
||||
- Do NOT modify storage (token/tunnelId remain valid)
|
||||
- Clear heartbeat interval
|
||||
- Invoke registered `onExit` callback → `TunnelRegistry` handles retry with
|
||||
exponential backoff (existing behavior)
|
||||
- On retry, `start(port)` finds the saved state, pings worker (still alive),
|
||||
and reuses the token → same public URL after reconnect
|
||||
|
||||
### Existing TunnelRegistry Changes
|
||||
|
||||
**`tunnel-registry.ts` — `createProvider()`:** Add one case:
|
||||
|
||||
```ts
|
||||
case 'openacp':
|
||||
return new OpenACPTunnelProvider(this.providerOptions, this.binDir ?? '', this.storage)
|
||||
```
|
||||
|
||||
`TunnelRegistry` receives a `storage: PluginStorage` constructor argument
|
||||
(required — `TunnelService` always passes `ctx.storage` down). If provider is
|
||||
`openacp` and `storage` is absent, `createProvider()` must throw with a clear
|
||||
error rather than failing silently at runtime.
|
||||
|
||||
**`tunnel-service.ts` — `TunnelService` constructor:** Accept and forward
|
||||
`storage` to `TunnelRegistry`.
|
||||
|
||||
### Tunnel Plugin Changes
|
||||
|
||||
**`plugins/tunnel/index.ts`:**
|
||||
|
||||
1. Add `'storage:read', 'storage:write'` to `permissions` array.
|
||||
2. Pass `ctx.storage` to `TunnelService` constructor.
|
||||
3. Update both `install()` and `configure()` provider selection lists to include
|
||||
`openacp` as the first (default) option:
|
||||
```
|
||||
openacp — OpenACP Managed (recommended, no account needed)
|
||||
cloudflare — Cloudflare quick tunnel
|
||||
ngrok — ngrok (requires auth token)
|
||||
bore — bore (self-hostable)
|
||||
tailscale — Tailscale Funnel
|
||||
```
|
||||
4. Default provider in `install()` when migrating from legacy config: keep
|
||||
existing value to avoid disrupting current users.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling & Fallback
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| Worker unreachable on `create` | Log error, throw — `TunnelRegistry` retries with backoff |
|
||||
| Worker returns 429 (IP rate limit) | Same as above — retry backoff |
|
||||
| `cloudflared` binary missing | `OpenACPTunnelProvider` calls `ensureCloudflared()` as fallback (reuses existing install logic) |
|
||||
| `cloudflared` exits unexpectedly | Clear heartbeat, fire `onExit` → registry retries; on retry, saved state is reused if still alive |
|
||||
| Worker unreachable on `ping` | Log warning, do not throw — tunnel continues running |
|
||||
| Worker unreachable on `DELETE` | Log warning, continue — cron will cleanup after TTL |
|
||||
| Saved token rejected by cloudflared | `start()` receives error → delete state entry → create new tunnel |
|
||||
|
||||
---
|
||||
|
||||
## Backward Compatibility
|
||||
|
||||
- Existing users with `provider: 'cloudflare'` in their config are unaffected.
|
||||
`CloudflareTunnelProvider` is unchanged.
|
||||
- `openacp` is only the default for **new installs** going through the
|
||||
interactive `install()` wizard. Existing installs keep their current provider.
|
||||
- No config migrations needed.
|
||||
|
||||
---
|
||||
|
||||
## Project Layout (final)
|
||||
|
||||
```
|
||||
openacp-workspace/
|
||||
OpenACP/ ← core changes
|
||||
src/plugins/tunnel/
|
||||
providers/openacp.ts ← NEW provider
|
||||
tunnel-registry.ts ← add 'openacp' case + storage param
|
||||
tunnel-service.ts ← forward storage param
|
||||
index.ts ← permissions + storage + install options
|
||||
openacp-tunnel-worker/ ← NEW Cloudflare Worker project
|
||||
src/
|
||||
index.ts
|
||||
routes/create.ts, ping.ts, destroy.ts
|
||||
lib/cloudflare-api.ts, rate-limit.ts, subdomain.ts
|
||||
cron.ts
|
||||
wrangler.toml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- User accounts or per-user quotas (shared API key + IP rate limit is sufficient for v1)
|
||||
- Custom domains per user
|
||||
- Tunnel analytics or usage dashboard
|
||||
- Migration of existing `cloudflare` users to `openacp`
|
||||
127
docs/superpowers/specs/2026-04-02-plugins-api-design.md
Normal file
127
docs/superpowers/specs/2026-04-02-plugins-api-design.md
Normal file
@ -0,0 +1,127 @@
|
||||
# Plugins API Design
|
||||
|
||||
## Overview
|
||||
|
||||
Add a `/api/v1/plugins` route group to the `api-server` plugin to expose plugin management
|
||||
capabilities to the OpenACP-App UI. Enables listing installed plugins, fetching the marketplace,
|
||||
and managing plugin state (enable/disable/uninstall) with hot-reload via `LifecycleManager`.
|
||||
|
||||
## New Endpoints
|
||||
|
||||
### GET /plugins
|
||||
|
||||
List all installed plugins from `PluginRegistry`, enriched with live runtime state from
|
||||
`LifecycleManager`.
|
||||
|
||||
**Response:**
|
||||
```ts
|
||||
{
|
||||
plugins: Array<{
|
||||
name: string // e.g. "@openacp/telegram"
|
||||
version: string
|
||||
description?: string
|
||||
source: 'builtin' | 'npm' | 'local'
|
||||
enabled: boolean // from PluginRegistry
|
||||
loaded: boolean // currently in lifecycleManager.loadedPlugins
|
||||
failed: boolean // in lifecycleManager.failedPlugins
|
||||
essential: boolean // see "Field Resolution" below
|
||||
hasConfigure: boolean // see "Field Resolution" below
|
||||
}>
|
||||
}
|
||||
```
|
||||
|
||||
**Field Resolution for `essential` and `hasConfigure`:**
|
||||
|
||||
These fields come from the plugin definition (`OpenACPPlugin`), not the registry. Resolution order:
|
||||
|
||||
1. **Loaded plugins**: definition is in `lifecycleManager.loadOrder` → read directly.
|
||||
2. **Failed plugins**: definition is still in `lifecycleManager.loadOrder` (added before boot fails) → read directly.
|
||||
3. **Disabled builtin plugins**: look up by name in `corePlugins` array.
|
||||
4. **Disabled npm plugins not loaded**: definition is unavailable → default `essential: false`, `hasConfigure: false`.
|
||||
|
||||
### GET /plugins/marketplace
|
||||
|
||||
Proxy to `RegistryClient.getRegistry()`. Cached per `RegistryClient` TTL (1 minute).
|
||||
Each plugin entry includes an `installed` boolean derived from `PluginRegistry`.
|
||||
|
||||
**Response:**
|
||||
```ts
|
||||
{
|
||||
plugins: Array<RegistryPlugin & { installed: boolean }>
|
||||
categories: Array<{ id: string; name: string; icon: string }>
|
||||
}
|
||||
```
|
||||
|
||||
Returns 503 with `{ error: "Marketplace unavailable" }` if registry fetch fails and no cache exists.
|
||||
|
||||
### POST /plugins/:name/enable
|
||||
|
||||
Enable a plugin: sets `enabled = true` in `PluginRegistry`, then hot-loads the plugin.
|
||||
|
||||
**Loading logic by source:**
|
||||
- `builtin`: plugin definition is in `corePlugins` — call `lifecycleManager.boot([plugin])` directly.
|
||||
- `npm` / `local`: dynamically import the module via `importFromDir(name, pluginsDir)`, then call
|
||||
`lifecycleManager.boot([plugin])`. If import fails, return 500 with message "Plugin module could
|
||||
not be loaded. Try restarting the server."
|
||||
|
||||
**Responses:**
|
||||
- **404** if plugin not in registry
|
||||
- No-op if plugin is already loaded (idempotent, still returns 200)
|
||||
- **500** if `boot()` fails (plugin enters `failed` state) or import fails
|
||||
|
||||
### POST /plugins/:name/disable
|
||||
|
||||
Disable a plugin: calls `lifecycleManager.unloadPlugin(name)`, then sets `enabled = false`
|
||||
in `PluginRegistry`.
|
||||
|
||||
- **404** if plugin not in registry
|
||||
- **409** if plugin `essential: true` — refuse with message "Essential plugins cannot be disabled"
|
||||
- No-op if plugin is already unloaded (still sets `enabled = false`, returns 200)
|
||||
|
||||
### DELETE /plugins/:name
|
||||
|
||||
Uninstall a plugin: calls `lifecycleManager.unloadPlugin(name)`, removes from `PluginRegistry`,
|
||||
saves registry.
|
||||
|
||||
- **400** if `source === 'builtin'` — refuse with message "Builtin plugins cannot be uninstalled. Use disable instead."
|
||||
- **404** if plugin not in registry
|
||||
- Does NOT remove npm package from disk (matches CLI behavior — user can re-enable by re-registering)
|
||||
|
||||
## RouteDeps Changes
|
||||
|
||||
`RouteDeps` in `routes/types.ts` needs one new optional field:
|
||||
|
||||
```ts
|
||||
lifecycleManager?: LifecycleManager
|
||||
```
|
||||
|
||||
Populated when registering the plugins route in `api-server/index.ts`.
|
||||
|
||||
Note: `settingsManager` is NOT needed here — plugin settings are managed by the plugins themselves,
|
||||
not by plugin management endpoints.
|
||||
|
||||
## Authorization
|
||||
|
||||
All plugin routes require auth + `system:admin` scope (same as restart endpoint).
|
||||
|
||||
## Instance Context
|
||||
|
||||
The `lifecycleManager` is scoped to the running instance's `instanceRoot`. Plugin operations
|
||||
always affect the connected instance only.
|
||||
|
||||
## Restart vs Hot-reload
|
||||
|
||||
| Action | Restart needed? | Method |
|
||||
|-----------------------------|-----------------|--------------------------------------------------|
|
||||
| Install npm plugin | Yes | CLI command shown in app, app shows restart cmd |
|
||||
| Enable builtin plugin | No | `lifecycleManager.boot()` from `corePlugins` |
|
||||
| Enable npm plugin | No (best effort)| `importFromDir()` + `lifecycleManager.boot()` |
|
||||
| Disable plugin | No | `lifecycleManager.unloadPlugin()` |
|
||||
| Uninstall plugin | No | `lifecycleManager.unloadPlugin()` |
|
||||
| Configure plugin (settings) | Yes | CLI command shown in app, app shows restart cmd |
|
||||
|
||||
## File Location
|
||||
|
||||
`src/plugins/api-server/routes/plugins.ts`
|
||||
|
||||
Registered in `src/plugins/api-server/index.ts` under prefix `/plugins` with auth enabled.
|
||||
@ -0,0 +1,45 @@
|
||||
# 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.
|
||||
@ -0,0 +1,392 @@
|
||||
# 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 |
|
||||
368
docs/superpowers/specs/2026-04-03-security-hardening-design.md
Normal file
368
docs/superpowers/specs/2026-04-03-security-hardening-design.md
Normal file
@ -0,0 +1,368 @@
|
||||
# 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
|
||||
130
docs/superpowers/specs/2026-04-03-session-list-history-design.md
Normal file
130
docs/superpowers/specs/2026-04-03-session-list-history-design.md
Normal file
@ -0,0 +1,130 @@
|
||||
# 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
|
||||
127
docs/superpowers/specs/2026-04-04-file-attachment-api-design.md
Normal file
127
docs/superpowers/specs/2026-04-04-file-attachment-api-design.md
Normal file
@ -0,0 +1,127 @@
|
||||
# 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)
|
||||
@ -0,0 +1,102 @@
|
||||
# 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
|
||||
@ -0,0 +1,212 @@
|
||||
# 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
|
||||
120
docs/superpowers/specs/2026-04-05-onboard-channel-setup-fix.md
Normal file
120
docs/superpowers/specs/2026-04-05-onboard-channel-setup-fix.md
Normal file
@ -0,0 +1,120 @@
|
||||
# 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.
|
||||
246
docs/superpowers/specs/2026-04-05-telegram-topics-ux-design.md
Normal file
246
docs/superpowers/specs/2026-04-05-telegram-topics-ux-design.md
Normal file
@ -0,0 +1,246 @@
|
||||
# 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") |
|
||||
@ -0,0 +1,143 @@
|
||||
# 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.
|
||||
@ -0,0 +1,129 @@
|
||||
# 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
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@openacp/cli",
|
||||
"version": "2026.401.7",
|
||||
"version": "2026.408.1",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@ -43,27 +43,25 @@
|
||||
"@agentclientprotocol/claude-agent-acp": "^0.24.2",
|
||||
"@agentclientprotocol/sdk": "^0.16.0",
|
||||
"@clack/prompts": "^1.1.0",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/swagger": "^9.7.0",
|
||||
"@fastify/swagger-ui": "^5.2.5",
|
||||
"@inquirer/prompts": "^8.3.2",
|
||||
"diff": "^8.0.3",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"fastify": "^5.8.4",
|
||||
"fastify-type-provider-zod": "~5.1.0",
|
||||
"grammy": "^1.41.1",
|
||||
"ignore": "^7.0.5",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"nanoid": "^5.0.0",
|
||||
"node-wav": "^0.0.2",
|
||||
"ogg-opus-decoder": "^1.7.3",
|
||||
"ora": "^9.3.0",
|
||||
"p-queue": "^9.1.0",
|
||||
"pino": "^10.3.1",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"pino-roll": "^4.0.0",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"shiki": "^4.0.2",
|
||||
"sanitize-html": "^2.17.2",
|
||||
"zod": "^3.25.0",
|
||||
"zod-to-json-schema": "^3.25.2"
|
||||
},
|
||||
@ -73,6 +71,7 @@
|
||||
"@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",
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@openacp/plugin-sdk",
|
||||
"version": "2026.401.7",
|
||||
"version": "2026.406.3",
|
||||
"description": "SDK for building OpenACP plugins — types, base classes, and testing utilities",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@ -18,6 +18,9 @@ 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,
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import type {
|
||||
PluginContext, PluginStorage, CommandDef, CommandResponse,
|
||||
OutgoingMessage,
|
||||
OutgoingMessage, MenuItem,
|
||||
} from '@openacp/cli'
|
||||
|
||||
export interface TestContextOpts {
|
||||
@ -112,6 +112,11 @@ 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> {
|
||||
|
||||
@ -2,7 +2,6 @@ import type { InstallContext, TerminalIO, SettingsAPI } from '@openacp/cli'
|
||||
|
||||
export interface TestInstallContextOpts {
|
||||
pluginName: string
|
||||
legacyConfig?: Record<string, unknown>
|
||||
terminalResponses?: Record<string, unknown[]>
|
||||
}
|
||||
|
||||
@ -123,7 +122,6 @@ export function createTestInstallContext(opts: TestInstallContextOpts): InstallC
|
||||
pluginName: opts.pluginName,
|
||||
terminal,
|
||||
settings,
|
||||
legacyConfig: opts.legacyConfig,
|
||||
dataDir: '/tmp/openacp-test-data',
|
||||
log: silentLog,
|
||||
// Test-specific
|
||||
|
||||
836
pnpm-lock.yaml
generated
836
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -30,7 +30,9 @@ $ERROR_C = "$ESC[38;2;239;68;68m" # red #ef4444
|
||||
$MUTED = "$ESC[38;2;90;100;128m" # text-muted #5a6480
|
||||
$NC = "$ESC[0m"
|
||||
|
||||
$NODE_MIN_MAJOR = 22
|
||||
$INSTALLER_VERSION = "1.0.1"
|
||||
|
||||
$NODE_MIN_MAJOR = 20
|
||||
|
||||
function Write-Msg {
|
||||
param(
|
||||
@ -50,6 +52,7 @@ 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 ""
|
||||
}
|
||||
|
||||
@ -204,14 +207,29 @@ 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
|
||||
}
|
||||
|
||||
@ -223,7 +241,7 @@ function Install-OpenACPNpm {
|
||||
while ($attempt -lt $maxRetries) {
|
||||
$attempt++
|
||||
try {
|
||||
$lastOutput = & npm install -g $spec 2>&1
|
||||
$lastOutput = & $npmExe install -g -- "$spec" 2>&1
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Msg -Level success -Message "Installed $spec via npm"
|
||||
return
|
||||
@ -235,7 +253,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
|
||||
}
|
||||
}
|
||||
@ -390,8 +408,9 @@ 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 = (& npm prefix -g 2>$null).Trim()
|
||||
$npmPrefix = (& $npmExe prefix -g 2>$null).Trim()
|
||||
if ($npmPrefix) {
|
||||
Add-ToPath -Dir $npmPrefix
|
||||
}
|
||||
@ -412,12 +431,13 @@ function Main {
|
||||
|
||||
$openacp = Get-Command openacp -ErrorAction SilentlyContinue
|
||||
if (-not $openacp) {
|
||||
# Also check npm global bin directly
|
||||
# Also check npm global prefix directly
|
||||
try {
|
||||
$npmBin = (& npm bin -g 2>$null).Trim()
|
||||
if ($npmBin -and (Test-Path (Join-Path $npmBin 'openacp.cmd'))) {
|
||||
$env:Path = "$env:Path;$npmBin"
|
||||
Add-ToPath -Dir $npmBin
|
||||
$npmForPrefix = Resolve-NpmExecutable
|
||||
$npmPrefix = (& $npmForPrefix prefix -g 2>$null).Trim()
|
||||
if ($npmPrefix -and (Test-Path (Join-Path $npmPrefix 'openacp.cmd'))) {
|
||||
$env:Path = "$env:Path;$npmPrefix"
|
||||
Add-ToPath -Dir $npmPrefix
|
||||
$openacp = Get-Command openacp -ErrorAction SilentlyContinue
|
||||
}
|
||||
} catch {}
|
||||
|
||||
@ -15,12 +15,23 @@ 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=()
|
||||
@ -239,7 +250,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" "modern installer mode")"
|
||||
hint="$("$GUM" style --foreground "#5a6480" "installer v${INSTALLER_VERSION}")"
|
||||
card="$(printf '%s\n%s\n%s' "$title" "$tagline" "$hint")"
|
||||
"$GUM" style --border rounded --border-foreground "#6366f1" --padding "1 2" "$card"
|
||||
echo ""
|
||||
@ -249,6 +260,7 @@ 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 ""
|
||||
}
|
||||
|
||||
@ -630,6 +642,22 @@ EOF
|
||||
|
||||
# ─── Section 5: Node.js Detection & Installation ──────────────────────────────
|
||||
|
||||
ensure_xcode_clt() {
|
||||
if [[ "$OS" != "macos" ]]; then
|
||||
return 0
|
||||
fi
|
||||
if xcode-select -p &>/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
ui_info "Xcode Command Line Tools not found — installing..."
|
||||
xcode-select --install 2>/dev/null || true
|
||||
ui_info "A dialog appeared — click Install and wait for it to complete"
|
||||
until xcode-select -p &>/dev/null 2>&1; do
|
||||
sleep 5
|
||||
done
|
||||
ui_success "Xcode Command Line Tools installed"
|
||||
}
|
||||
|
||||
node_major_version() {
|
||||
if ! command -v node &>/dev/null; then
|
||||
return 1
|
||||
@ -670,11 +698,13 @@ 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"
|
||||
ui_success "Node.js v$(node -v | cut -d'v' -f2) found (${node_path})"
|
||||
return 0
|
||||
else
|
||||
ui_info "Node.js $(node -v) found, need v${NODE_MIN_VERSION}+"
|
||||
ui_info "Node.js $(node -v) found at ${node_path}, need v${NODE_MIN_VERSION}+"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
@ -684,14 +714,28 @@ check_node() {
|
||||
}
|
||||
|
||||
ensure_default_node_active_shell() {
|
||||
if node_is_at_least_required; then
|
||||
return 0
|
||||
fi
|
||||
# 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
|
||||
# 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"
|
||||
fi
|
||||
if [[ -n "$nvm_sh" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "${NVM_DIR}/nvm.sh" 2>/dev/null || true
|
||||
source "$nvm_sh" 2>/dev/null || true
|
||||
if node_is_at_least_required; then
|
||||
return 0
|
||||
fi
|
||||
@ -713,6 +757,23 @@ 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
|
||||
}
|
||||
|
||||
@ -725,45 +786,100 @@ 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
|
||||
# Install via Homebrew
|
||||
if ! command -v brew &>/dev/null; then
|
||||
ui_info "Homebrew not found, installing"
|
||||
run_quiet_step "Installing Homebrew" bash -c 'NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
|
||||
if [[ -f "/opt/homebrew/bin/brew" ]]; then
|
||||
eval "$(/opt/homebrew/bin/brew shellenv)"
|
||||
elif [[ -f "/usr/local/bin/brew" ]]; then
|
||||
eval "$(/usr/local/bin/brew shellenv)"
|
||||
fi
|
||||
fi
|
||||
ui_info "Installing Node.js via Homebrew"
|
||||
run_quiet_step "Installing node@${NODE_DEFAULT_MAJOR}" brew install "node@${NODE_DEFAULT_MAJOR}"
|
||||
brew link "node@${NODE_DEFAULT_MAJOR}" --overwrite --force 2>/dev/null || true
|
||||
|
||||
# Ensure brew node is on PATH
|
||||
local brew_node_prefix=""
|
||||
brew_node_prefix="$(brew --prefix "node@${NODE_DEFAULT_MAJOR}" 2>/dev/null || true)"
|
||||
if [[ -n "$brew_node_prefix" && -x "${brew_node_prefix}/bin/node" ]]; then
|
||||
export PATH="${brew_node_prefix}/bin:$PATH"
|
||||
hash -r 2>/dev/null || true
|
||||
ensure_xcode_clt
|
||||
# Install via nvm (no sudo required)
|
||||
if [[ -z "${NVM_DIR:-}" ]] && [[ ! -s "${HOME}/.nvm/nvm.sh" ]] && [[ ! -s "${XDG_CONFIG_HOME:-}/nvm/nvm.sh" ]]; then
|
||||
ui_info "Installing nvm (Node Version Manager)"
|
||||
local nvm_install
|
||||
nvm_install="$(mktempfile)"
|
||||
download_file "https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.4/install.sh" "$nvm_install"
|
||||
run_quiet_step "Installing nvm" bash "$nvm_install"
|
||||
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
|
||||
|
||||
ui_success "Node.js installed"
|
||||
if [[ -s "${NVM_DIR:-${HOME}/.nvm}/nvm.sh" ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source "${NVM_DIR:-${HOME}/.nvm}/nvm.sh"
|
||||
ui_info "Installing Node.js v${NODE_DEFAULT_MAJOR} via nvm"
|
||||
run_quiet_step "Installing Node.js" nvm install "${NODE_DEFAULT_MAJOR}"
|
||||
nvm use "${NODE_DEFAULT_MAJOR}" 2>/dev/null || true
|
||||
nvm alias default "${NODE_DEFAULT_MAJOR}" 2>/dev/null || true
|
||||
else
|
||||
ui_error "Could not install nvm. Please install Node.js ${NODE_DEFAULT_MAJOR} manually: https://nodejs.org"
|
||||
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
|
||||
# Check for nvm first, install it if not present.
|
||||
# Note: nvm is a shell function, not a binary — command -v nvm is unreliable.
|
||||
# Always detect nvm via NVM_DIR / nvm.sh presence.
|
||||
if [[ -z "${NVM_DIR:-}" ]] && [[ ! -s "${HOME}/.nvm/nvm.sh" ]]; then
|
||||
if [[ -z "${NVM_DIR:-}" ]] && [[ ! -s "${HOME}/.nvm/nvm.sh" ]] && [[ ! -s "${XDG_CONFIG_HOME:-}/nvm/nvm.sh" ]]; then
|
||||
ui_info "Installing nvm (Node Version Manager)"
|
||||
local nvm_install
|
||||
nvm_install="$(mktempfile)"
|
||||
download_file "https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh" "$nvm_install"
|
||||
download_file "https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.4/install.sh" "$nvm_install"
|
||||
run_quiet_step "Installing nvm" bash "$nvm_install"
|
||||
export NVM_DIR="${HOME}/.nvm"
|
||||
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
|
||||
@ -828,6 +944,11 @@ 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
|
||||
}
|
||||
@ -923,17 +1044,22 @@ 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
|
||||
|
||||
if [[ -w "$npm_prefix" || -w "$npm_prefix/lib" ]]; then
|
||||
# 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
|
||||
return 0
|
||||
fi
|
||||
|
||||
@ -1201,9 +1327,18 @@ 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}"
|
||||
@ -1239,6 +1374,14 @@ 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
|
||||
@ -1259,9 +1402,11 @@ 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
|
||||
install_openacp_from_git "$GIT_DIR"
|
||||
else
|
||||
if ! check_git; then
|
||||
install_git
|
||||
if ! command -v git &>/dev/null; then
|
||||
@ -1270,8 +1415,8 @@ main() {
|
||||
fi
|
||||
hash -r 2>/dev/null || true
|
||||
fi
|
||||
fix_npm_permissions
|
||||
|
||||
install_openacp_from_git "$GIT_DIR"
|
||||
else
|
||||
local install_spec=""
|
||||
install_spec="$(resolve_package_install_spec "$INSTALL_TAG")"
|
||||
install_openacp_npm "$install_spec"
|
||||
@ -1326,6 +1471,14 @@ 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..."
|
||||
@ -1333,10 +1486,10 @@ main() {
|
||||
exec </dev/tty
|
||||
exec "$OPENACP_BIN"
|
||||
else
|
||||
ui_info "Run openacp to start the setup wizard"
|
||||
ui_info "Then run: openacp"
|
||||
fi
|
||||
else
|
||||
ui_info "Run openacp to get started"
|
||||
ui_info "Then run: openacp"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
@ -32,7 +32,7 @@ function createMockSession() {
|
||||
setName: vi.fn(),
|
||||
finish: vi.fn(),
|
||||
fail: vi.fn(),
|
||||
updateConfigOptions: vi.fn(),
|
||||
updateConfigOptions: vi.fn().mockResolvedValue(undefined),
|
||||
toAcpStateSnapshot: vi.fn().mockReturnValue({}),
|
||||
}) as unknown as Session
|
||||
}
|
||||
|
||||
@ -26,6 +26,7 @@ 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(),
|
||||
@ -36,22 +37,13 @@ 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", args: [], workingDirectory: "/tmp/ws" },
|
||||
},
|
||||
security: {
|
||||
maxConcurrentSessions: 5,
|
||||
sessionTimeoutMinutes: 60,
|
||||
allowedUserIds: [],
|
||||
},
|
||||
channels: {
|
||||
telegram: { enabled: false, botToken: "secret-token", chatId: 0 },
|
||||
},
|
||||
agents: { claude: { command: "claude-agent-acp", args: [], env: {} } },
|
||||
workspace: { baseDir: "~/openacp-workspace" },
|
||||
logging: {
|
||||
level: "info",
|
||||
@ -60,30 +52,26 @@ 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: {},
|
||||
speech: {
|
||||
stt: { provider: null, providers: {} },
|
||||
tts: { provider: null, providers: {} },
|
||||
},
|
||||
agentSwitch: { labelHistory: true },
|
||||
})),
|
||||
save: vi.fn(),
|
||||
setPath: vi.fn(),
|
||||
resolveWorkspace: vi.fn(() => "/tmp/ws"),
|
||||
on: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
},
|
||||
settingsManager: {
|
||||
loadSettings: vi.fn().mockResolvedValue({}),
|
||||
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,
|
||||
@ -107,7 +95,7 @@ describe("ApiServer", () => {
|
||||
} catch { /* ignore */ }
|
||||
});
|
||||
|
||||
async function startServer(portOverride?: number) {
|
||||
async function startServer(portOverride?: number, lifecycleManagerOverride?: unknown) {
|
||||
// Create or load the test secret
|
||||
const dir = path.dirname(secretFilePath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
@ -146,13 +134,16 @@ describe("ApiServer", () => {
|
||||
|
||||
const authPreHandler = createAuthPreHandler(() => secret, () => jwtSecret, tokenStore);
|
||||
|
||||
const deps = {
|
||||
const deps: Record<string, unknown> = {
|
||||
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));
|
||||
@ -308,7 +299,13 @@ describe("ApiServer", () => {
|
||||
{ status: "active" },
|
||||
{ status: "initializing" },
|
||||
]);
|
||||
const port = await startServer();
|
||||
// Provide lifecycleManager with settingsManager returning maxConcurrentSessions=5
|
||||
const mockLifecycleManager = {
|
||||
settingsManager: {
|
||||
loadSettings: vi.fn().mockResolvedValue({ maxConcurrentSessions: 5 }),
|
||||
},
|
||||
};
|
||||
const port = await startServer(undefined, mockLifecycleManager);
|
||||
|
||||
const res = await apiFetch(port, "/api/v1/sessions", { method: "POST" });
|
||||
expect(res.status).toBe(429);
|
||||
@ -357,28 +354,38 @@ describe("ApiServer", () => {
|
||||
});
|
||||
|
||||
it("GET /api/sessions returns session list", async () => {
|
||||
mockCore.sessionManager.listSessions.mockReturnValueOnce([
|
||||
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([
|
||||
{
|
||||
id: "abc",
|
||||
agentName: "claude",
|
||||
agent: "claude",
|
||||
status: "active",
|
||||
name: "Fix bug",
|
||||
workingDirectory: "/tmp/a",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
clientOverrides: { bypassPermissions: false },
|
||||
workspace: "/tmp/a",
|
||||
channelId: "api",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
lastActiveAt: null,
|
||||
dangerousMode: false,
|
||||
queueDepth: 0,
|
||||
promptRunning: false,
|
||||
configOptions: undefined,
|
||||
capabilities: null,
|
||||
isLive: true,
|
||||
},
|
||||
{
|
||||
id: "def",
|
||||
agentName: "codex",
|
||||
agent: "codex",
|
||||
status: "initializing",
|
||||
name: undefined,
|
||||
workingDirectory: "/tmp/b",
|
||||
createdAt: new Date("2026-01-02T00:00:00Z"),
|
||||
clientOverrides: { bypassPermissions: false },
|
||||
name: null,
|
||||
workspace: "/tmp/b",
|
||||
channelId: "api",
|
||||
createdAt: "2026-01-02T00:00:00.000Z",
|
||||
lastActiveAt: null,
|
||||
dangerousMode: false,
|
||||
queueDepth: 0,
|
||||
promptRunning: false,
|
||||
configOptions: undefined,
|
||||
capabilities: null,
|
||||
isLive: true,
|
||||
},
|
||||
]);
|
||||
const port = await startServer();
|
||||
@ -405,20 +412,24 @@ describe("ApiServer", () => {
|
||||
|
||||
it("GET /api/sessions returns extended fields", async () => {
|
||||
const created = new Date("2026-01-01T00:00:00Z");
|
||||
mockCore.sessionManager.listSessions.mockReturnValueOnce([
|
||||
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([
|
||||
{
|
||||
id: "abc",
|
||||
agentName: "claude",
|
||||
agent: "claude",
|
||||
status: "active",
|
||||
name: "Test",
|
||||
workingDirectory: "/tmp",
|
||||
createdAt: created,
|
||||
clientOverrides: { bypassPermissions: true },
|
||||
workspace: "/tmp",
|
||||
channelId: "api",
|
||||
createdAt: created.toISOString(),
|
||||
lastActiveAt: null,
|
||||
dangerousMode: 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");
|
||||
@ -570,7 +581,22 @@ describe("ApiServer", () => {
|
||||
|
||||
// ===== New endpoint tests =====
|
||||
|
||||
it("GET /api/health returns system health", async () => {
|
||||
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 () => {
|
||||
mockCore.sessionManager.listSessions.mockReturnValueOnce([
|
||||
{ status: "active" },
|
||||
{ status: "initializing" },
|
||||
@ -584,7 +610,7 @@ describe("ApiServer", () => {
|
||||
]);
|
||||
const port = await startServer();
|
||||
|
||||
const res = await apiFetch(port, "/api/v1/system/health");
|
||||
const res = await apiFetch(port, "/api/v1/system/health/details");
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.status).toBe("ok");
|
||||
@ -638,7 +664,6 @@ 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");
|
||||
});
|
||||
|
||||
@ -662,7 +687,7 @@ describe("ApiServer", () => {
|
||||
const data = await res.json();
|
||||
expect(data.ok).toBe(true);
|
||||
expect(data.sessionId).toBe("abc123");
|
||||
expect(mockSession.enqueuePrompt).toHaveBeenCalledWith("Hello world");
|
||||
expect(mockSession.enqueuePrompt).toHaveBeenCalledWith("Hello world", undefined, expect.objectContaining({ sourceAdapterId: "api" }), expect.any(String));
|
||||
});
|
||||
|
||||
it("POST /api/sessions/:id/prompt returns 404 for unknown session", async () => {
|
||||
@ -821,7 +846,7 @@ describe("ApiServer", () => {
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const data = await res.json();
|
||||
expect(data.error).toContain("Missing message");
|
||||
expect(data.error).toContain("Required");
|
||||
});
|
||||
|
||||
it("POST /api/restart returns 200 and triggers restart", async () => {
|
||||
@ -893,9 +918,9 @@ describe("ApiServer", () => {
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.ok).toBe(true);
|
||||
expect(mockCore.configManager.save).toHaveBeenCalledWith(
|
||||
{ defaultAgent: "codex" },
|
||||
expect(mockCore.configManager.setPath).toHaveBeenCalledWith(
|
||||
"defaultAgent",
|
||||
"codex",
|
||||
);
|
||||
});
|
||||
|
||||
@ -983,23 +1008,23 @@ describe("ApiServer", () => {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
path: "security.maxConcurrentSessions",
|
||||
value: 10,
|
||||
path: "logging.level",
|
||||
value: "debug",
|
||||
}),
|
||||
});
|
||||
const data1 = (await res1.json()) as any;
|
||||
expect(data1.ok).toBe(true);
|
||||
expect(data1.needsRestart).toBe(false);
|
||||
|
||||
// Non-hot-reloadable field — should need restart
|
||||
// Unknown/unsafe field — should return 403
|
||||
const res2 = await apiFetch(port, "/api/v1/config", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: "tunnel.enabled", value: false }),
|
||||
body: JSON.stringify({ path: "nonexistent.field", value: false }),
|
||||
});
|
||||
const data2 = (await res2.json()) as any;
|
||||
expect(data2.ok).toBe(true);
|
||||
expect(data2.needsRestart).toBe(true);
|
||||
expect(res2.status).toBe(403);
|
||||
expect(data2.error).toContain("cannot be modified");
|
||||
});
|
||||
|
||||
it("GET /api/events returns SSE headers", async () => {
|
||||
@ -1012,7 +1037,7 @@ describe("ApiServer", () => {
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("text/event-stream");
|
||||
expect(res.headers.get("cache-control")).toBe("no-cache");
|
||||
expect(res.headers.get("cache-control")).toBe("no-cache, no-transform");
|
||||
controller.abort();
|
||||
});
|
||||
|
||||
@ -1028,6 +1053,9 @@ describe("ApiServer", () => {
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Read initial `: connected` comment
|
||||
await reader.read();
|
||||
|
||||
// Wait for SSE connection to be registered
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
@ -1038,7 +1066,7 @@ describe("ApiServer", () => {
|
||||
status: "initializing",
|
||||
});
|
||||
|
||||
// Read SSE data
|
||||
// Read SSE event data
|
||||
const { value } = await reader.read();
|
||||
const text = decoder.decode(value);
|
||||
expect(text).toContain("event: session:created");
|
||||
@ -1058,6 +1086,9 @@ describe("ApiServer", () => {
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Read initial `: connected` comment
|
||||
await reader.read();
|
||||
|
||||
// Wait for SSE connection to be registered
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
@ -1413,19 +1444,19 @@ describe("ApiServer", () => {
|
||||
|
||||
it("rejects invalid config values (string for number field)", async () => {
|
||||
const port = await startServer();
|
||||
// Pass a string where Zod expects a number — ConfigSchema.safeParse will fail
|
||||
// Pass a string where the field expects a number (sessionStore.ttlDays is a number field in registry)
|
||||
const res = await apiFetch(port, "/api/v1/config", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
path: "security.maxConcurrentSessions",
|
||||
path: "sessionStore.ttlDays",
|
||||
value: "not-a-number",
|
||||
}),
|
||||
});
|
||||
// Fails Zod validation → 400
|
||||
// Fails type validation → 400
|
||||
expect(res.status).toBe(400);
|
||||
const data = (await res.json()) as any;
|
||||
expect(data.error).toBe("Validation failed");
|
||||
expect(data.error.code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
// --- Redact config with arrays ---
|
||||
@ -1433,17 +1464,6 @@ 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",
|
||||
@ -1452,24 +1472,16 @@ 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();
|
||||
|
||||
@ -1508,10 +1520,8 @@ 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
|
||||
// Use raw fetch without auth — public /health requires no token
|
||||
const res = await globalThis.fetch(`http://127.0.0.1:${port}/api/v1/system/health`);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
@ -1525,7 +1535,7 @@ describe("ApiServer", () => {
|
||||
});
|
||||
|
||||
it("accepts requests with valid auth token", async () => {
|
||||
mockCore.sessionManager.listSessions.mockReturnValueOnce([]);
|
||||
mockCore.sessionManager.listAllSessions.mockReturnValueOnce([]);
|
||||
const port = await startServer();
|
||||
const token = readTestSecret();
|
||||
const res = await globalThis.fetch(
|
||||
|
||||
@ -304,17 +304,17 @@ describe('CLI command args parsing', () => {
|
||||
|
||||
describe('cmdInstall', () => {
|
||||
it('parses package name from args[0]', () => {
|
||||
const { args } = simulateDispatch(['install', '@openacp/adapter-discord'])
|
||||
const { args } = simulateDispatch(['install', '@openacp/discord-adapter'])
|
||||
const pkg = args[0]
|
||||
expect(pkg).toBe('@openacp/adapter-discord')
|
||||
expect(pkg).toBe('@openacp/discord-adapter')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cmdUninstall', () => {
|
||||
it('parses package name from args[0]', () => {
|
||||
const { args } = simulateDispatch(['uninstall', '@openacp/adapter-discord'])
|
||||
const { args } = simulateDispatch(['uninstall', '@openacp/discord-adapter'])
|
||||
const pkg = args[0]
|
||||
expect(pkg).toBe('@openacp/adapter-discord')
|
||||
expect(pkg).toBe('@openacp/discord-adapter')
|
||||
})
|
||||
})
|
||||
|
||||
@ -332,9 +332,9 @@ describe('CLI command args parsing', () => {
|
||||
})
|
||||
|
||||
it('parses install package from args[1]', () => {
|
||||
const { args } = simulateDispatch(['plugin', 'add', '@openacp/adapter-discord'])
|
||||
const { args } = simulateDispatch(['plugin', 'add', '@openacp/discord-adapter'])
|
||||
expect(args[0]).toBe('add')
|
||||
expect(args[1]).toBe('@openacp/adapter-discord')
|
||||
expect(args[1]).toBe('@openacp/discord-adapter')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -3,8 +3,6 @@ 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',
|
||||
}
|
||||
|
||||
@ -33,42 +31,70 @@ 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')
|
||||
expect(config2.security.maxConcurrentSessions).toBe(20)
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@ -35,11 +35,8 @@ 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))
|
||||
|
||||
@ -58,20 +55,50 @@ describe('ConfigManager.resolveWorkspace', () => {
|
||||
expect(fs.existsSync(result)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves absolute path directly', async () => {
|
||||
it('allows absolute path outside baseDir when allowExternalWorkspaces is true (default)', async () => {
|
||||
await configManager.load()
|
||||
const absPath = path.join(tmpDir, 'custom-workspace')
|
||||
const result = configManager.resolveWorkspace(absPath)
|
||||
expect(result).toBe(absPath)
|
||||
// /tmp exists on all systems; with allowExternalWorkspaces: true (default) it should be accepted
|
||||
const result = configManager.resolveWorkspace('/tmp')
|
||||
expect(result).toBe('/tmp')
|
||||
})
|
||||
|
||||
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('allows absolute path under baseDir', async () => {
|
||||
await configManager.load()
|
||||
const underBase = path.join(tmpDir, 'workspace', 'sub-project')
|
||||
const result = configManager.resolveWorkspace(underBase)
|
||||
expect(result).toBe(underBase)
|
||||
expect(fs.existsSync(result)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves tilde path', async () => {
|
||||
it('allows baseDir itself as absolute path', async () => {
|
||||
await configManager.load()
|
||||
const result = configManager.resolveWorkspace('~/test-workspace-openacp')
|
||||
expect(result).toBe(path.join(os.homedir(), 'test-workspace-openacp'))
|
||||
// Cleanup
|
||||
fs.rmSync(result, { recursive: true, force: true })
|
||||
const base = path.join(tmpDir, 'workspace')
|
||||
const result = configManager.resolveWorkspace(base)
|
||||
expect(result).toBe(base)
|
||||
expect(fs.existsSync(result)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves named workspace under baseDir', async () => {
|
||||
@ -111,25 +138,16 @@ 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 () => {
|
||||
@ -139,22 +157,6 @@ 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)
|
||||
@ -162,13 +164,6 @@ 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)
|
||||
@ -197,27 +192,6 @@ 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', () => {
|
||||
@ -230,10 +204,7 @@ 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()
|
||||
@ -259,14 +230,14 @@ describe('ConfigManager.save and hot-reload', () => {
|
||||
configManager.on('config:changed', (e) => events.push(e))
|
||||
|
||||
await configManager.save(
|
||||
{ security: { maxConcurrentSessions: 10 } },
|
||||
'security.maxConcurrentSessions',
|
||||
{ defaultAgent: 'codex' },
|
||||
'defaultAgent',
|
||||
)
|
||||
|
||||
expect(events).toHaveLength(1)
|
||||
expect(events[0]).toMatchObject({
|
||||
path: 'security.maxConcurrentSessions',
|
||||
value: 10,
|
||||
path: 'defaultAgent',
|
||||
value: 'codex',
|
||||
})
|
||||
})
|
||||
|
||||
@ -280,9 +251,8 @@ describe('ConfigManager.save and hot-reload', () => {
|
||||
})
|
||||
|
||||
it('deep merges nested config', async () => {
|
||||
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)
|
||||
await configManager.save({ workspace: { baseDir: '~/custom-workspace' } })
|
||||
// Other workspace fields should still exist after deep merge
|
||||
expect(configManager.get().workspace.baseDir).toBe('~/custom-workspace')
|
||||
})
|
||||
})
|
||||
|
||||
@ -3,6 +3,7 @@ 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", () => {
|
||||
@ -88,6 +89,72 @@ 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",
|
||||
|
||||
@ -43,6 +43,7 @@ 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' },
|
||||
@ -228,14 +229,8 @@ 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()
|
||||
|
||||
@ -12,6 +12,32 @@ describe('ViewerStore', () => {
|
||||
store.destroy()
|
||||
})
|
||||
|
||||
describe('storeFile() — path outside workspace (issue #195)', () => {
|
||||
it('returns null for openacp files dir outside workspace without throwing', () => {
|
||||
// Regression: voice attachments saved to ~/.openacp/files/<sessionId>/ are
|
||||
// always outside the agent workspace. storeFile must return null silently
|
||||
// (not throw, not WARN) — callers tolerate null by skipping viewer links.
|
||||
const id = store.storeFile(
|
||||
'sess-1',
|
||||
'/home/codex/.openacp/files/wAmobthop7go/voice.wav',
|
||||
'binary data',
|
||||
'/home/codex/flutter_web_test',
|
||||
)
|
||||
expect(id).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for storeDiff with openacp files dir outside workspace', () => {
|
||||
const id = store.storeDiff(
|
||||
'sess-1',
|
||||
'/home/codex/.openacp/files/wAmobthop7go/voice.wav',
|
||||
'old',
|
||||
'new',
|
||||
'/home/codex/flutter_web_test',
|
||||
)
|
||||
expect(id).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('storeFile()', () => {
|
||||
it('stores a file and returns an id', () => {
|
||||
const id = store.storeFile('sess-1', '/workspace/test.ts', 'const x = 1', '/workspace')
|
||||
|
||||
@ -9,10 +9,12 @@ describe("buildWelcomeMessage", () => {
|
||||
totalCount: 0,
|
||||
agents: ["claude"],
|
||||
defaultAgent: "claude",
|
||||
workspace: "/home/user/workspace",
|
||||
};
|
||||
const msg = buildWelcomeMessage(ctx);
|
||||
expect(msg).toContain("OpenACP is ready");
|
||||
expect(msg).toContain("No sessions yet");
|
||||
expect(msg).toContain("/home/user/workspace");
|
||||
expect(msg).not.toContain("Agents:");
|
||||
});
|
||||
|
||||
@ -23,6 +25,7 @@ describe("buildWelcomeMessage", () => {
|
||||
totalCount: 5,
|
||||
agents: ["claude", "codex"],
|
||||
defaultAgent: "claude",
|
||||
workspace: "/home/user/workspace",
|
||||
};
|
||||
const msg = buildWelcomeMessage(ctx);
|
||||
expect(msg).toContain("2 active / 5 total");
|
||||
@ -38,6 +41,7 @@ describe("buildWelcomeMessage", () => {
|
||||
totalCount: 5,
|
||||
agents: ["claude"],
|
||||
defaultAgent: "claude",
|
||||
workspace: "/home/user/workspace",
|
||||
};
|
||||
const msg = buildWelcomeMessage(ctx);
|
||||
expect(msg).toContain("1 active");
|
||||
@ -53,6 +57,7 @@ describe("buildWelcomeMessage", () => {
|
||||
totalCount: 3,
|
||||
agents: ["claude"],
|
||||
defaultAgent: "claude",
|
||||
workspace: "/home/user/workspace",
|
||||
};
|
||||
const msg = buildWelcomeMessage(ctx);
|
||||
expect(msg).toContain("0 active / 3 total");
|
||||
@ -66,6 +71,7 @@ describe("buildWelcomeMessage", () => {
|
||||
totalCount: 10,
|
||||
agents: ["claude"],
|
||||
defaultAgent: "claude",
|
||||
workspace: "/home/user/workspace",
|
||||
};
|
||||
const msg = buildWelcomeMessage(ctx);
|
||||
expect(msg).toContain("errors");
|
||||
|
||||
11
src/cli.ts
11
src/cli.ts
@ -22,6 +22,7 @@ import {
|
||||
cmdUpdate,
|
||||
cmdDefault,
|
||||
cmdAdopt,
|
||||
cmdInstances,
|
||||
cmdIntegrate,
|
||||
cmdDoctor,
|
||||
cmdAgents,
|
||||
@ -30,6 +31,7 @@ import {
|
||||
cmdDev,
|
||||
cmdAttach,
|
||||
cmdRemote,
|
||||
cmdSetup,
|
||||
} from './cli/commands/index.js'
|
||||
import { resolveInstanceRoot } from './core/instance/instance-context.js'
|
||||
|
||||
@ -84,10 +86,11 @@ resolvedInstanceRoot = resolveInstanceRoot({
|
||||
const noInstanceCommands: Record<string, () => Promise<void>> = {
|
||||
'--help': async () => printHelp(),
|
||||
'-h': async () => printHelp(),
|
||||
'--version': () => cmdVersion(),
|
||||
'-v': () => cmdVersion(),
|
||||
'--version': () => cmdVersion(args),
|
||||
'-v': () => cmdVersion(args),
|
||||
'update': () => cmdUpdate(args),
|
||||
'adopt': () => cmdAdopt(args),
|
||||
'instances': async () => cmdInstances(args, flags),
|
||||
'integrate': () => cmdIntegrate(args),
|
||||
'dev': () => cmdDev(args),
|
||||
}
|
||||
@ -122,7 +125,8 @@ async function main() {
|
||||
const registry = new InstanceRegistry(path.join(getGlobal(), 'instances.json'))
|
||||
await registry.load()
|
||||
const entry = registry.getByRoot(envRoot)
|
||||
const id = entry?.id ?? 'unknown'
|
||||
const { randomUUID } = await import('node:crypto')
|
||||
const id = entry?.id ?? randomUUID()
|
||||
const ctx = createInstanceContext({
|
||||
id,
|
||||
root: envRoot,
|
||||
@ -155,6 +159,7 @@ async function main() {
|
||||
'onboard': (r) => cmdOnboard(r),
|
||||
'attach': (r) => cmdAttach(args, r),
|
||||
'remote': (r) => cmdRemote(args, r),
|
||||
'setup': (r) => cmdSetup(args, r),
|
||||
}
|
||||
|
||||
const handler = command ? instanceCommands[command] : undefined
|
||||
|
||||
85
src/cli/__tests__/integrate.test.ts
Normal file
85
src/cli/__tests__/integrate.test.ts
Normal file
@ -0,0 +1,85 @@
|
||||
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.");
|
||||
});
|
||||
});
|
||||
120
src/cli/__tests__/output.test.ts
Normal file
120
src/cli/__tests__/output.test.ts
Normal file
@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
describe('isJsonMode', () => {
|
||||
it('returns true when args contain --json', async () => {
|
||||
const { isJsonMode } = await import('../output.js')
|
||||
expect(isJsonMode(['list', '--json'])).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when args do not contain --json', async () => {
|
||||
const { isJsonMode } = await import('../output.js')
|
||||
expect(isJsonMode(['list'])).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for empty args', async () => {
|
||||
const { isJsonMode } = await import('../output.js')
|
||||
expect(isJsonMode([])).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when --json is the only arg', async () => {
|
||||
const { isJsonMode } = await import('../output.js')
|
||||
expect(isJsonMode(['--json'])).toBe(true)
|
||||
})
|
||||
|
||||
it('does not match partial flags like --json-pretty', async () => {
|
||||
const { isJsonMode } = await import('../output.js')
|
||||
expect(isJsonMode(['--json-pretty'])).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('jsonSuccess', () => {
|
||||
let logSpy: ReturnType<typeof vi.spyOn>
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(() => {
|
||||
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
|
||||
throw new Error('process.exit')
|
||||
}) as any)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs valid JSON with success: true and data', async () => {
|
||||
const { jsonSuccess } = await import('../output.js')
|
||||
try { jsonSuccess({ foo: 'bar' }) } catch {}
|
||||
expect(logSpy).toHaveBeenCalledOnce()
|
||||
const output = logSpy.mock.calls[0][0] as string
|
||||
const parsed = JSON.parse(output)
|
||||
expect(parsed).toEqual({ success: true, data: { foo: 'bar' } })
|
||||
})
|
||||
|
||||
it('calls process.exit(0)', async () => {
|
||||
const { jsonSuccess } = await import('../output.js')
|
||||
try { jsonSuccess({}) } catch {}
|
||||
expect(exitSpy).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('outputs single-line JSON (no newlines in output)', async () => {
|
||||
const { jsonSuccess } = await import('../output.js')
|
||||
try { jsonSuccess({ nested: { a: 1, b: [2, 3] } }) } catch {}
|
||||
const output = logSpy.mock.calls[0][0] as string
|
||||
expect(output).not.toContain('\n')
|
||||
JSON.parse(output) // should not throw
|
||||
})
|
||||
})
|
||||
|
||||
describe('jsonError', () => {
|
||||
let logSpy: ReturnType<typeof vi.spyOn>
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(() => {
|
||||
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
|
||||
throw new Error('process.exit')
|
||||
}) as any)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs valid JSON with success: false and error object', async () => {
|
||||
const { jsonError, ErrorCodes } = await import('../output.js')
|
||||
try { jsonError(ErrorCodes.DAEMON_NOT_RUNNING, 'Not running') } catch {}
|
||||
const output = logSpy.mock.calls[0][0] as string
|
||||
const parsed = JSON.parse(output)
|
||||
expect(parsed).toEqual({
|
||||
success: false,
|
||||
error: { code: 'DAEMON_NOT_RUNNING', message: 'Not running' },
|
||||
})
|
||||
})
|
||||
|
||||
it('calls process.exit(1)', async () => {
|
||||
const { jsonError, ErrorCodes } = await import('../output.js')
|
||||
try { jsonError(ErrorCodes.UNKNOWN_ERROR, 'oops') } catch {}
|
||||
expect(exitSpy).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('outputs single-line JSON', async () => {
|
||||
const { jsonError, ErrorCodes } = await import('../output.js')
|
||||
try { jsonError(ErrorCodes.API_ERROR, 'msg') } catch {}
|
||||
const output = logSpy.mock.calls[0][0] as string
|
||||
expect(output).not.toContain('\n')
|
||||
JSON.parse(output)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ErrorCodes', () => {
|
||||
it('all values are unique strings', async () => {
|
||||
const { ErrorCodes } = await import('../output.js')
|
||||
const values = Object.values(ErrorCodes)
|
||||
expect(new Set(values).size).toBe(values.length)
|
||||
for (const v of values) {
|
||||
expect(typeof v).toBe('string')
|
||||
expect(v.length).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
})
|
||||
47
src/cli/commands/__tests__/adopt-json.test.ts
Normal file
47
src/cli/commands/__tests__/adopt-json.test.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../api-client.js', () => ({
|
||||
readApiPort: vi.fn().mockReturnValue(3000),
|
||||
apiCall: vi.fn().mockResolvedValue({
|
||||
json: () => Promise.resolve({ ok: true, sessionId: 'sess-1', threadId: 'thread-1', status: 'new' }),
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('adopt --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful adopt', async () => {
|
||||
const { cmdAdopt } = await import('../adopt.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAdopt(['claude', 'ext-session-1', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('sessionId', 'sess-1')
|
||||
expect(data).toHaveProperty('threadId', 'thread-1')
|
||||
expect(data).toHaveProperty('agent', 'claude')
|
||||
expect(data).toHaveProperty('status', 'new')
|
||||
})
|
||||
|
||||
it('outputs JSON error when missing arguments', async () => {
|
||||
const { cmdAdopt } = await import('../adopt.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAdopt(['--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
|
||||
it('outputs JSON error when daemon not running', async () => {
|
||||
const apiClient = await import('../../api-client.js')
|
||||
vi.mocked(apiClient.readApiPort).mockReturnValue(null)
|
||||
|
||||
const { cmdAdopt } = await import('../adopt.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAdopt(['claude', 'sess-1', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'DAEMON_NOT_RUNNING')
|
||||
})
|
||||
})
|
||||
63
src/cli/commands/__tests__/agents-json.test.ts
Normal file
63
src/cli/commands/__tests__/agents-json.test.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../../core/agents/agent-catalog.js', () => {
|
||||
class MockAgentCatalog {
|
||||
load = vi.fn()
|
||||
refreshRegistryIfStale = vi.fn().mockResolvedValue(undefined)
|
||||
getAvailable = vi.fn().mockReturnValue([
|
||||
{
|
||||
key: 'claude-code',
|
||||
name: 'Claude Code',
|
||||
version: '1.0.0',
|
||||
distribution: 'npm',
|
||||
description: 'AI coding agent',
|
||||
installed: true,
|
||||
available: true,
|
||||
missingDeps: [],
|
||||
},
|
||||
{
|
||||
key: 'gemini',
|
||||
name: 'Gemini CLI',
|
||||
version: '0.5.0',
|
||||
distribution: 'npm',
|
||||
description: 'Google Gemini agent',
|
||||
installed: false,
|
||||
available: true,
|
||||
missingDeps: [],
|
||||
},
|
||||
])
|
||||
}
|
||||
return { AgentCatalog: MockAgentCatalog }
|
||||
})
|
||||
|
||||
describe('agents list --json', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs envelope with agents array', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['list', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('agents')
|
||||
expect(Array.isArray(data.agents)).toBe(true)
|
||||
expect((data.agents as unknown[]).length).toBe(2)
|
||||
})
|
||||
|
||||
it('includes all required fields in each agent entry', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['list', '--json'], undefined)
|
||||
})
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
const agent = (data.agents as Record<string, unknown>[])[0]
|
||||
const fields = ['key', 'name', 'version', 'distribution', 'description', 'installed', 'available', 'missingDeps']
|
||||
for (const field of fields) {
|
||||
expect(agent).toHaveProperty(field)
|
||||
}
|
||||
})
|
||||
})
|
||||
121
src/cli/commands/__tests__/agents-subcommands-json.test.ts
Normal file
121
src/cli/commands/__tests__/agents-subcommands-json.test.ts
Normal file
@ -0,0 +1,121 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../../core/agents/agent-catalog.js', () => {
|
||||
class MockAgentCatalog {
|
||||
load = vi.fn()
|
||||
refreshRegistryIfStale = vi.fn().mockResolvedValue(undefined)
|
||||
getAvailable = vi.fn().mockReturnValue([])
|
||||
getInstalledAgent = vi.fn().mockImplementation((key: string) => {
|
||||
if (key === 'claude-code') {
|
||||
return {
|
||||
registryId: 'claude-code',
|
||||
name: 'Claude Code',
|
||||
version: '1.0.0',
|
||||
distribution: 'npm',
|
||||
command: 'npx',
|
||||
args: ['@anthropic-ai/claude-code'],
|
||||
env: {},
|
||||
installedAt: '2026-01-01T00:00:00Z',
|
||||
binaryPath: null,
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
findRegistryAgent = vi.fn().mockReturnValue(undefined)
|
||||
install = vi.fn().mockResolvedValue({ ok: true, agentKey: 'gemini' })
|
||||
uninstall = vi.fn().mockResolvedValue({ ok: true })
|
||||
getInstalledEntries = vi.fn().mockReturnValue({ 'claude-code': {} })
|
||||
}
|
||||
return { AgentCatalog: MockAgentCatalog }
|
||||
})
|
||||
|
||||
vi.mock('../../../core/agents/agent-dependencies.js', () => ({
|
||||
getAgentCapabilities: vi.fn().mockReturnValue({ integration: null }),
|
||||
getAgentSetup: vi.fn().mockReturnValue(undefined),
|
||||
}))
|
||||
|
||||
describe('agents info --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON for installed agent', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['info', 'claude-code', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('key', 'claude-code')
|
||||
expect(data).toHaveProperty('name', 'Claude Code')
|
||||
expect(data).toHaveProperty('installed', true)
|
||||
expect(data).toHaveProperty('version', '1.0.0')
|
||||
expect(data).toHaveProperty('distribution', 'npm')
|
||||
expect(data).toHaveProperty('command', 'npx')
|
||||
})
|
||||
|
||||
it('outputs JSON error for unknown agent', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['info', 'nonexistent', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'AGENT_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('outputs JSON error when no agent name provided', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['info', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('agents install --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful install', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['install', 'gemini', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('key', 'gemini')
|
||||
expect(data).toHaveProperty('installed', true)
|
||||
})
|
||||
|
||||
it('outputs JSON error when no agent name provided', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['install', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('agents uninstall --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful uninstall', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['uninstall', 'claude-code', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('key', 'claude-code')
|
||||
expect(data).toHaveProperty('uninstalled', true)
|
||||
})
|
||||
|
||||
it('outputs JSON error when no agent name provided', async () => {
|
||||
const { cmdAgents } = await import('../agents.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdAgents(['uninstall', '--json'], undefined)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
173
src/cli/commands/__tests__/api-json.test.ts
Normal file
173
src/cli/commands/__tests__/api-json.test.ts
Normal file
@ -0,0 +1,173 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../api-client.js', () => ({
|
||||
readApiPort: vi.fn().mockReturnValue(3000),
|
||||
removeStalePortFile: vi.fn(),
|
||||
apiCall: vi.fn().mockImplementation((_port: number, urlPath: string, options?: RequestInit) => {
|
||||
if (urlPath === '/api/sessions' && !options?.method) {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
sessions: [{ id: 'sess-1', agent: 'claude', status: 'active', name: 'Test' }],
|
||||
}),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/sessions' && options?.method === 'POST') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
sessionId: 'new-sess', agent: 'claude', workspace: '/tmp', status: 'active', channelId: 'tg',
|
||||
}),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/agents') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
agents: [{ name: 'claude', command: 'npx', args: [] }],
|
||||
default: 'claude',
|
||||
}),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/topics') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
topics: [{ sessionId: 's1', topicId: 1, name: 'Test', status: 'active', agentName: 'claude', lastActiveAt: '2026-01-01' }],
|
||||
}),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/health') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ status: 'ok', uptime: 3600, version: '2026.401.1' }),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/config' && !options?.method) {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ config: { defaultAgent: 'claude', runMode: 'daemon' } }),
|
||||
})
|
||||
}
|
||||
if (urlPath.startsWith('/api/sessions/') && options?.method === 'DELETE') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ cancelled: true }),
|
||||
})
|
||||
}
|
||||
// Default
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
|
||||
}),
|
||||
}))
|
||||
|
||||
// Mock the logger to prevent pino initialization errors
|
||||
vi.mock('../../../core/utils/log.js', () => ({
|
||||
muteLogger: vi.fn(),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
describe('api status --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('wraps API response in success envelope', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['status', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('sessions')
|
||||
expect((data.sessions as unknown[]).length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('api new --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('wraps session creation response', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['new', 'claude', '/tmp', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('sessionId', 'new-sess')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api agents --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('wraps agents response', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['agents', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('agents')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api topics --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('wraps topics response', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['topics', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('topics')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api health --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('wraps health response', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['health', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('status', 'ok')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api cancel --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs success on cancel', async () => {
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['cancel', 'sess-1', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('cancelled', true)
|
||||
expect(data).toHaveProperty('sessionId', 'sess-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api --json daemon not running', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs DAEMON_NOT_RUNNING error', async () => {
|
||||
const apiClient = await import('../../api-client.js')
|
||||
vi.mocked(apiClient.readApiPort).mockReturnValue(null)
|
||||
|
||||
const { cmdApi } = await import('../api.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdApi(['status', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'DAEMON_NOT_RUNNING')
|
||||
})
|
||||
})
|
||||
50
src/cli/commands/__tests__/config-json.test.ts
Normal file
50
src/cli/commands/__tests__/config-json.test.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../api-client.js', () => ({
|
||||
readApiPort: vi.fn().mockReturnValue(null),
|
||||
apiCall: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../core/config/config.js', () => ({
|
||||
ConfigManager: class {
|
||||
exists = vi.fn().mockResolvedValue(true)
|
||||
load = vi.fn().mockResolvedValue(undefined)
|
||||
save = vi.fn().mockResolvedValue(undefined)
|
||||
},
|
||||
ConfigSchema: { shape: { defaultAgent: {}, telegram: {}, security: {}, logging: {} } },
|
||||
}))
|
||||
|
||||
describe('config set --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful config set (file mode)', async () => {
|
||||
const { cmdConfig } = await import('../config.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdConfig(['set', 'defaultAgent', 'claude', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('path', 'defaultAgent')
|
||||
expect(data).toHaveProperty('value', 'claude')
|
||||
expect(data).toHaveProperty('needsRestart', false)
|
||||
})
|
||||
|
||||
it('outputs JSON error for unknown config key', async () => {
|
||||
const { cmdConfig } = await import('../config.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdConfig(['set', 'nonexistent', 'value', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'CONFIG_INVALID')
|
||||
})
|
||||
|
||||
it('outputs JSON error for missing arguments', async () => {
|
||||
const { cmdConfig } = await import('../config.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdConfig(['set', '--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
55
src/cli/commands/__tests__/daemon-json.test.ts
Normal file
55
src/cli/commands/__tests__/daemon-json.test.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../daemon.js', () => ({
|
||||
startDaemon: vi.fn().mockReturnValue({ pid: 12345 }),
|
||||
stopDaemon: vi.fn().mockResolvedValue({ stopped: true, pid: 12345 }),
|
||||
getPidPath: vi.fn().mockReturnValue('/tmp/test.pid'),
|
||||
markRunning: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../core/config/config.js', () => ({
|
||||
ConfigManager: class {
|
||||
exists = vi.fn().mockResolvedValue(true)
|
||||
load = vi.fn().mockResolvedValue(undefined)
|
||||
get = vi.fn().mockReturnValue({ logging: { logDir: '/tmp/logs' }, runMode: 'daemon', api: { port: 21420 } })
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../version.js', () => ({
|
||||
checkAndPromptUpdate: vi.fn().mockResolvedValue(undefined),
|
||||
getCurrentVersion: vi.fn().mockReturnValue('2026.401.1'),
|
||||
}))
|
||||
|
||||
vi.mock('../../instance-hint.js', () => ({
|
||||
printInstanceHint: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('stop --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful stop', async () => {
|
||||
const { cmdStop } = await import('../stop.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdStop(['--json'], '/tmp/test-instance')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('stopped', true)
|
||||
expect(data).toHaveProperty('pid', 12345)
|
||||
})
|
||||
})
|
||||
|
||||
describe('start --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful start', async () => {
|
||||
const { cmdStart } = await import('../start.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdStart(['--json'], '/tmp/test-instance')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('pid', 12345)
|
||||
})
|
||||
})
|
||||
61
src/cli/commands/__tests__/doctor-json.test.ts
Normal file
61
src/cli/commands/__tests__/doctor-json.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../../core/doctor/index.js', () => ({
|
||||
DoctorEngine: class {
|
||||
runAll = vi.fn().mockResolvedValue({
|
||||
categories: [
|
||||
{ name: 'Config', results: [{ status: 'pass', message: 'Config valid' }] },
|
||||
{ name: 'Agents', results: [{ status: 'warn', message: 'No agents installed' }] },
|
||||
],
|
||||
pendingFixes: [],
|
||||
summary: { passed: 1, warnings: 1, failed: 0, fixed: 0 },
|
||||
})
|
||||
},
|
||||
}))
|
||||
|
||||
describe('doctor --json', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON report with categories and summary', async () => {
|
||||
const { cmdDoctor } = await import('../doctor.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdDoctor(['--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('categories')
|
||||
expect(data).toHaveProperty('summary')
|
||||
expect((data.summary as Record<string, number>).passed).toBe(1)
|
||||
expect((data.summary as Record<string, number>).warnings).toBe(1)
|
||||
})
|
||||
|
||||
it('always exits 0 even with failures', async () => {
|
||||
// Override mock for this test by re-mocking before dynamic import
|
||||
vi.doMock('../../../core/doctor/index.js', () => ({
|
||||
DoctorEngine: class {
|
||||
runAll = vi.fn().mockResolvedValue({
|
||||
categories: [
|
||||
{ name: 'Config', results: [{ status: 'fail', message: 'Config broken' }] },
|
||||
],
|
||||
pendingFixes: [],
|
||||
summary: { passed: 0, warnings: 0, failed: 1, fixed: 0 },
|
||||
})
|
||||
},
|
||||
}))
|
||||
|
||||
const { cmdDoctor } = await import('../doctor.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdDoctor(['--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect((data.summary as Record<string, number>).failed).toBe(1)
|
||||
})
|
||||
})
|
||||
54
src/cli/commands/__tests__/helpers/json-test-utils.test.ts
Normal file
54
src/cli/commands/__tests__/helpers/json-test-utils.test.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './json-test-utils.js'
|
||||
|
||||
describe('captureJsonOutput', () => {
|
||||
it('captures stdout and exit code from jsonSuccess', async () => {
|
||||
const { jsonSuccess } = await import('../../../output.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
jsonSuccess({ test: true })
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const parsed = JSON.parse(result.stdout)
|
||||
expect(parsed.success).toBe(true)
|
||||
expect(parsed.data.test).toBe(true)
|
||||
})
|
||||
|
||||
it('captures stdout and exit code from jsonError', async () => {
|
||||
const { jsonError, ErrorCodes } = await import('../../../output.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
jsonError(ErrorCodes.UNKNOWN_ERROR, 'test error')
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
const parsed = JSON.parse(result.stdout)
|
||||
expect(parsed.success).toBe(false)
|
||||
expect(parsed.error.code).toBe('UNKNOWN_ERROR')
|
||||
})
|
||||
|
||||
it('rethrows non-exit errors', async () => {
|
||||
await expect(captureJsonOutput(async () => {
|
||||
throw new Error('real error')
|
||||
})).rejects.toThrow('real error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('expectValidJsonSuccess', () => {
|
||||
it('returns data for valid success output', () => {
|
||||
const data = expectValidJsonSuccess('{"success":true,"data":{"x":1}}')
|
||||
expect(data).toEqual({ x: 1 })
|
||||
})
|
||||
|
||||
it('throws for error output', () => {
|
||||
expect(() => expectValidJsonSuccess('{"success":false,"error":{"code":"X","message":"m"}}')).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('expectValidJsonError', () => {
|
||||
it('returns error for valid error output', () => {
|
||||
const err = expectValidJsonError('{"success":false,"error":{"code":"FOO","message":"bar"}}', 'FOO')
|
||||
expect(err).toEqual({ code: 'FOO', message: 'bar' })
|
||||
})
|
||||
|
||||
it('throws when code does not match', () => {
|
||||
expect(() => expectValidJsonError('{"success":false,"error":{"code":"FOO","message":"bar"}}', 'BAR')).toThrow()
|
||||
})
|
||||
})
|
||||
68
src/cli/commands/__tests__/helpers/json-test-utils.ts
Normal file
68
src/cli/commands/__tests__/helpers/json-test-utils.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
export interface CapturedOutput {
|
||||
stdout: string
|
||||
exitCode: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* IMPORTANT: When using this in test files that also use vi.mock() at top level,
|
||||
* add vi.resetModules() in beforeEach to avoid mock leaking between tests.
|
||||
*/
|
||||
export async function captureJsonOutput(fn: () => Promise<void>): Promise<CapturedOutput> {
|
||||
let stdout = ''
|
||||
let exitCode: number | null = null
|
||||
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
|
||||
stdout += args.map(String).join(' ')
|
||||
})
|
||||
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code: number) => {
|
||||
exitCode = code ?? 0
|
||||
throw new Error(`process.exit(${code})`)
|
||||
}) as any)
|
||||
|
||||
try {
|
||||
await fn()
|
||||
} catch (err) {
|
||||
if (!(err instanceof Error && err.message.startsWith('process.exit'))) {
|
||||
throw err
|
||||
}
|
||||
} finally {
|
||||
logSpy.mockRestore()
|
||||
exitSpy.mockRestore()
|
||||
}
|
||||
|
||||
return { stdout, exitCode }
|
||||
}
|
||||
|
||||
export function expectValidJsonSuccess(stdout: string, dataShape?: Record<string, unknown>): Record<string, unknown> {
|
||||
const parsed = JSON.parse(stdout)
|
||||
if (parsed.success !== true) {
|
||||
throw new Error(`Expected success: true, got: ${JSON.stringify(parsed)}`)
|
||||
}
|
||||
if (!('data' in parsed)) {
|
||||
throw new Error('Missing "data" field in success response')
|
||||
}
|
||||
if (dataShape) {
|
||||
for (const [key] of Object.entries(dataShape)) {
|
||||
if (!(key in parsed.data)) {
|
||||
throw new Error(`Missing key "${key}" in data`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export function expectValidJsonError(stdout: string, expectedCode?: string): { code: string; message: string } {
|
||||
const parsed = JSON.parse(stdout)
|
||||
if (parsed.success !== false) {
|
||||
throw new Error(`Expected success: false, got: ${JSON.stringify(parsed)}`)
|
||||
}
|
||||
if (!parsed.error || typeof parsed.error.code !== 'string' || typeof parsed.error.message !== 'string') {
|
||||
throw new Error(`Invalid error shape: ${JSON.stringify(parsed.error)}`)
|
||||
}
|
||||
if (expectedCode && parsed.error.code !== expectedCode) {
|
||||
throw new Error(`Expected error code "${expectedCode}", got "${parsed.error.code}"`)
|
||||
}
|
||||
return parsed.error
|
||||
}
|
||||
82
src/cli/commands/__tests__/install-json.test.ts
Normal file
82
src/cli/commands/__tests__/install-json.test.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
vi.mock('node:child_process', () => ({
|
||||
execSync: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock the logger to prevent pino initialization errors
|
||||
vi.mock('../../../core/utils/log.js', () => ({
|
||||
muteLogger: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('install --json', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-install-test-'))
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON on successful install', async () => {
|
||||
const { cmdInstall } = await import('../install.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdInstall(['@test/plugin', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('plugin', '@test/plugin')
|
||||
expect(data).toHaveProperty('installed', true)
|
||||
})
|
||||
|
||||
it('outputs JSON error when package name missing', async () => {
|
||||
const { cmdInstall } = await import('../install.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdInstall(['--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('uninstall --json', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-uninstall-test-'))
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON on successful uninstall', async () => {
|
||||
const { cmdUninstall } = await import('../uninstall.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdUninstall(['@test/plugin', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('plugin', '@test/plugin')
|
||||
expect(data).toHaveProperty('uninstalled', true)
|
||||
})
|
||||
|
||||
it('outputs JSON error when package name missing', async () => {
|
||||
const { cmdUninstall } = await import('../uninstall.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdUninstall(['--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'MISSING_ARGUMENT')
|
||||
})
|
||||
})
|
||||
119
src/cli/commands/__tests__/plugins-json.test.ts
Normal file
119
src/cli/commands/__tests__/plugins-json.test.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
describe('plugins --json', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-plugins-test-'))
|
||||
fs.writeFileSync(path.join(tmpDir, 'plugins.json'), JSON.stringify({
|
||||
installed: {
|
||||
'telegram': { version: '1.0.0', enabled: true, source: 'builtin', description: 'Telegram adapter', installedAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z', settingsPath: '' },
|
||||
},
|
||||
}))
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON with plugins array', async () => {
|
||||
const { cmdPlugins } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugins(['--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('plugins')
|
||||
expect(Array.isArray(data.plugins)).toBe(true)
|
||||
})
|
||||
|
||||
it('includes all required fields in each plugin entry', async () => {
|
||||
const { cmdPlugins } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugins(['--json'], tmpDir)
|
||||
})
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
const plugins = data.plugins as Record<string, unknown>[]
|
||||
expect(plugins.length).toBe(1)
|
||||
const plugin = plugins[0]
|
||||
expect(plugin).toHaveProperty('name', 'telegram')
|
||||
expect(plugin).toHaveProperty('version', '1.0.0')
|
||||
expect(plugin).toHaveProperty('enabled', true)
|
||||
expect(plugin).toHaveProperty('source', 'builtin')
|
||||
expect(plugin).toHaveProperty('description', 'Telegram adapter')
|
||||
})
|
||||
|
||||
it('outputs empty array when no plugins installed', async () => {
|
||||
fs.writeFileSync(path.join(tmpDir, 'plugins.json'), JSON.stringify({ installed: {} }))
|
||||
const { cmdPlugins } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugins(['--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data.plugins).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('plugin enable/disable --json', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-plugin-toggle-'))
|
||||
fs.writeFileSync(path.join(tmpDir, 'plugins.json'), JSON.stringify({
|
||||
installed: {
|
||||
'telegram': { version: '1.0.0', enabled: true, source: 'builtin', description: 'Telegram adapter', installedAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z', settingsPath: '' },
|
||||
},
|
||||
}))
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON when disabling a plugin', async () => {
|
||||
const { cmdPlugin } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugin(['disable', 'telegram', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toEqual({ plugin: 'telegram', enabled: false })
|
||||
})
|
||||
|
||||
it('outputs JSON when enabling a plugin', async () => {
|
||||
const { cmdPlugin } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugin(['enable', 'telegram', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toEqual({ plugin: 'telegram', enabled: true })
|
||||
})
|
||||
|
||||
it('outputs JSON error for unknown plugin', async () => {
|
||||
const { cmdPlugin } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugin(['enable', 'nonexistent', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'PLUGIN_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('outputs JSON error when disabling unknown plugin', async () => {
|
||||
const { cmdPlugin } = await import('../plugins.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdPlugin(['disable', 'nonexistent', '--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(1)
|
||||
expectValidJsonError(result.stdout, 'PLUGIN_NOT_FOUND')
|
||||
})
|
||||
})
|
||||
48
src/cli/commands/__tests__/restart-json.test.ts
Normal file
48
src/cli/commands/__tests__/restart-json.test.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../daemon.js', () => ({
|
||||
startDaemon: vi.fn().mockReturnValue({ pid: 99999 }),
|
||||
stopDaemon: vi.fn().mockResolvedValue({ stopped: false }),
|
||||
getPidPath: vi.fn().mockReturnValue('/tmp/test.pid'),
|
||||
markRunning: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../core/config/config.js', () => ({
|
||||
ConfigManager: class {
|
||||
exists = vi.fn().mockResolvedValue(true)
|
||||
load = vi.fn().mockResolvedValue(undefined)
|
||||
get = vi.fn().mockReturnValue({ logging: { logDir: '/tmp/logs' }, runMode: 'foreground' })
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../version.js', () => ({
|
||||
checkAndPromptUpdate: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
vi.mock('../../instance-hint.js', () => ({
|
||||
printInstanceHint: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../core/instance/instance-context.js', () => ({
|
||||
createInstanceContext: vi.fn().mockReturnValue({}),
|
||||
getGlobalRoot: vi.fn().mockReturnValue('/tmp/global'),
|
||||
}))
|
||||
|
||||
describe('restart --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('forces daemon mode when --json is passed even if config says foreground', async () => {
|
||||
const { cmdRestart } = await import('../restart.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdRestart(['--json'], '/tmp/test-instance')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('pid', 99999)
|
||||
|
||||
// Verify startDaemon was called (not startServer for foreground)
|
||||
const daemon = await import('../../daemon.js')
|
||||
expect(daemon.startDaemon).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
73
src/cli/commands/__tests__/setup.test.ts
Normal file
73
src/cli/commands/__tests__/setup.test.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
describe('cmdSetup', () => {
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-setup-test-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('writes config.json with correct fields when all flags provided', async () => {
|
||||
const { cmdSetup } = await import('../setup.js');
|
||||
await cmdSetup(
|
||||
['--workspace', '/tmp/my-workspace', '--agent', 'claude-code', '--run-mode', 'daemon'],
|
||||
tmpDir,
|
||||
);
|
||||
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
expect(fs.existsSync(configPath)).toBe(true);
|
||||
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
expect(config.workspace.baseDir).toBe('/tmp/my-workspace');
|
||||
expect(config.defaultAgent).toBe('claude-code');
|
||||
expect(config.runMode).toBe('daemon');
|
||||
expect(config.autoStart).toBe(false);
|
||||
});
|
||||
|
||||
it('uses first agent when comma-separated agents passed', async () => {
|
||||
const { cmdSetup } = await import('../setup.js');
|
||||
await cmdSetup(['--workspace', '/tmp/ws', '--agent', 'claude-code,gemini'], tmpDir);
|
||||
|
||||
const config = JSON.parse(fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8'));
|
||||
expect(config.defaultAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('outputs JSON result when --json flag is passed', async () => {
|
||||
const { captureJsonOutput, expectValidJsonSuccess } = await import('./helpers/json-test-utils.js');
|
||||
const { cmdSetup } = await import('../setup.js');
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdSetup(
|
||||
['--workspace', '/tmp/ws', '--agent', 'claude-code', '--json'],
|
||||
tmpDir,
|
||||
);
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const data = expectValidJsonSuccess(result.stdout);
|
||||
expect(data).toHaveProperty('configPath');
|
||||
expect((data.configPath as string)).toContain('config.json');
|
||||
});
|
||||
|
||||
it('exits with code 1 when --workspace is missing', async () => {
|
||||
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('process.exit called'); }) as any);
|
||||
|
||||
const { cmdSetup } = await import('../setup.js');
|
||||
await expect(cmdSetup(['--agent', 'claude-code'], tmpDir)).rejects.toThrow('process.exit called');
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('exits with code 1 when --agent is missing', async () => {
|
||||
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('process.exit called'); }) as any);
|
||||
|
||||
const { cmdSetup } = await import('../setup.js');
|
||||
await expect(cmdSetup(['--workspace', '/tmp/ws'], tmpDir)).rejects.toThrow('process.exit called');
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
33
src/cli/commands/__tests__/status-json.test.ts
Normal file
33
src/cli/commands/__tests__/status-json.test.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess } from './helpers/json-test-utils.js'
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
describe('status --json', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-status-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON with instance info when daemon is not running', async () => {
|
||||
fs.writeFileSync(path.join(tmpDir, 'config.json'), JSON.stringify({ instanceName: 'test' }))
|
||||
|
||||
const { cmdStatus } = await import('../status.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdStatus(['--json'], tmpDir)
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('name')
|
||||
expect(data).toHaveProperty('status')
|
||||
expect(data.status).toBe('offline')
|
||||
expect(data.pid).toBeNull()
|
||||
})
|
||||
})
|
||||
89
src/cli/commands/__tests__/tunnel-json.test.ts
Normal file
89
src/cli/commands/__tests__/tunnel-json.test.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess, expectValidJsonError } from './helpers/json-test-utils.js'
|
||||
|
||||
vi.mock('../../api-client.js', () => ({
|
||||
readApiPort: vi.fn().mockReturnValue(3000),
|
||||
apiCall: vi.fn().mockImplementation((_port: number, urlPath: string, options?: RequestInit) => {
|
||||
if (urlPath === '/api/tunnel/list') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([
|
||||
{ port: 8080, label: 'web', publicUrl: 'https://example.trycloudflare.com', status: 'active' },
|
||||
]),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/tunnel' && options?.method === 'POST') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ port: 8080, publicUrl: 'https://example.trycloudflare.com' }),
|
||||
})
|
||||
}
|
||||
if (urlPath === '/api/tunnel' && options?.method === 'DELETE') {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
|
||||
}
|
||||
if (urlPath.startsWith('/api/tunnel/') && options?.method === 'DELETE') {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
|
||||
}
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('tunnel list --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON with tunnels array', async () => {
|
||||
const { cmdTunnel } = await import('../tunnel.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdTunnel(['list', '--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('tunnels')
|
||||
expect(Array.isArray(data.tunnels)).toBe(true)
|
||||
expect((data.tunnels as any[])[0].port).toBe(8080)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel add --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON with port and publicUrl', async () => {
|
||||
const { cmdTunnel } = await import('../tunnel.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdTunnel(['add', '8080', '--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('port', 8080)
|
||||
expect(data).toHaveProperty('publicUrl')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel stop --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful stop', async () => {
|
||||
const { cmdTunnel } = await import('../tunnel.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdTunnel(['stop', '8080', '--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('port', 8080)
|
||||
expect(data).toHaveProperty('stopped', true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel stop-all --json', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('outputs JSON on successful stop-all', async () => {
|
||||
const { cmdTunnel } = await import('../tunnel.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdTunnel(['stop-all', '--json'], '/tmp/test')
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('stopped', true)
|
||||
})
|
||||
})
|
||||
27
src/cli/commands/__tests__/version-json.test.ts
Normal file
27
src/cli/commands/__tests__/version-json.test.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { captureJsonOutput, expectValidJsonSuccess } from './helpers/json-test-utils.js'
|
||||
|
||||
describe('version --json', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('outputs JSON with version string', async () => {
|
||||
const { cmdVersion } = await import('../version.js')
|
||||
const result = await captureJsonOutput(async () => {
|
||||
await cmdVersion(['--json'])
|
||||
})
|
||||
expect(result.exitCode).toBe(0)
|
||||
const data = expectValidJsonSuccess(result.stdout)
|
||||
expect(data).toHaveProperty('version')
|
||||
expect(typeof data.version).toBe('string')
|
||||
expect((data.version as string).length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('outputs plain text without --json', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const { cmdVersion } = await import('../version.js')
|
||||
await cmdVersion([])
|
||||
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('openacp v'))
|
||||
})
|
||||
})
|
||||
@ -1,5 +1,6 @@
|
||||
import { readApiPort } from '../api-client.js'
|
||||
import { wantsHelp } from './helpers.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
|
||||
export async function cmdAdopt(args: string[]): Promise<void> {
|
||||
if (wantsHelp(args)) {
|
||||
@ -16,6 +17,7 @@ export async function cmdAdopt(args: string[]): Promise<void> {
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--cwd <path> Working directory for the session (default: current dir)
|
||||
--channel <name> Target channel adapter (e.g. telegram, discord). Default: first registered
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
Transfers an existing agent session into OpenACP so it appears
|
||||
@ -29,10 +31,23 @@ as a messaging thread. Requires a running daemon.
|
||||
return
|
||||
}
|
||||
|
||||
const agent = args[0];
|
||||
const sessionId = args[1];
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
// Parse positional args — skip known flags and their values
|
||||
const skipFlags = new Set(['--json', '-h', '--help'])
|
||||
const skipWithValue = new Set(['--cwd', '--channel'])
|
||||
const positional: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (skipWithValue.has(args[i]!)) { i++; continue }
|
||||
if (skipFlags.has(args[i]!)) continue
|
||||
positional.push(args[i]!)
|
||||
}
|
||||
const agent = positional[0]
|
||||
const sessionId = positional[1]
|
||||
|
||||
if (!agent || !sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Missing required arguments: <agent> and <session_id>')
|
||||
console.log("Usage: openacp adopt <agent> <session_id> [--cwd <path>] [--channel <name>]");
|
||||
console.log("Example: openacp adopt claude abc123-def456 --cwd /path/to/project");
|
||||
process.exit(1);
|
||||
@ -45,6 +60,7 @@ as a messaging thread. Requires a running daemon.
|
||||
|
||||
const port = readApiPort();
|
||||
if (!port) {
|
||||
if (json) jsonError(ErrorCodes.DAEMON_NOT_RUNNING, 'OpenACP is not running. Start it with: openacp start')
|
||||
console.log("OpenACP is not running. Start it with: openacp start");
|
||||
process.exit(1);
|
||||
}
|
||||
@ -59,6 +75,7 @@ as a messaging thread. Requires a running daemon.
|
||||
const data = await res.json() as Record<string, unknown>;
|
||||
|
||||
if (data.ok) {
|
||||
if (json) jsonSuccess({ sessionId: data.sessionId, threadId: data.threadId, agent, status: data.status ?? 'new' })
|
||||
if (data.status === "existing") {
|
||||
console.log(`Session already active. Topic pinged.`);
|
||||
} else {
|
||||
@ -67,10 +84,13 @@ as a messaging thread. Requires a running daemon.
|
||||
console.log(` Session ID: ${data.sessionId}`);
|
||||
console.log(` Thread ID: ${data.threadId}`);
|
||||
} else {
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, `${(data.message as string) || (data.error as string) || 'Unknown error'}`)
|
||||
console.log(`Error: ${(data.message as string) || (data.error as string)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message.startsWith('process.exit')) throw err
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, `Failed to connect to OpenACP: ${err instanceof Error ? err.message : err}`)
|
||||
console.log(`Failed to connect to OpenACP: ${err instanceof Error ? err.message : err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { wantsHelp } from './helpers.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, ErrorCodes, muteForJson } from '../output.js'
|
||||
|
||||
async function createCatalog(instanceRoot?: string) {
|
||||
const { AgentCatalog } = await import("../../core/agents/agent-catalog.js");
|
||||
@ -27,6 +28,7 @@ export async function cmdAgents(args: string[], instanceRoot?: string): Promise<
|
||||
openacp agents refresh Force-refresh agent list from registry
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
@ -39,11 +41,14 @@ export async function cmdAgents(args: string[], instanceRoot?: string): Promise<
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract positional argument (first non-flag after subcommand)
|
||||
const positional = args.slice(1).find(a => !a.startsWith('-'));
|
||||
|
||||
switch (subcommand) {
|
||||
case "install":
|
||||
return agentsInstall(args[1], args.includes("--force"), wantsHelp(args), instanceRoot);
|
||||
return agentsInstall(positional, args.includes("--force"), wantsHelp(args), instanceRoot, isJsonMode(args));
|
||||
case "uninstall":
|
||||
return agentsUninstall(args[1], wantsHelp(args), instanceRoot);
|
||||
return agentsUninstall(positional, wantsHelp(args), instanceRoot, isJsonMode(args));
|
||||
case "refresh":
|
||||
if (wantsHelp(args)) {
|
||||
console.log(`
|
||||
@ -59,12 +64,12 @@ bypassing the normal staleness check.
|
||||
}
|
||||
return agentsRefresh(instanceRoot);
|
||||
case "info":
|
||||
return agentsInfo(args[1], wantsHelp(args), instanceRoot);
|
||||
return agentsInfo(positional, wantsHelp(args), instanceRoot, isJsonMode(args));
|
||||
case "run":
|
||||
return agentsRun(args[1], args.slice(2), wantsHelp(args), instanceRoot);
|
||||
case "list":
|
||||
case undefined:
|
||||
return agentsList(instanceRoot);
|
||||
return agentsList(instanceRoot, args.includes("--json"));
|
||||
default: {
|
||||
const { suggestMatch } = await import('../suggest.js');
|
||||
const agentSubcommands = ["install", "uninstall", "refresh", "info", "run", "list"];
|
||||
@ -77,12 +82,29 @@ bypassing the normal staleness check.
|
||||
}
|
||||
}
|
||||
|
||||
async function agentsList(instanceRoot?: string): Promise<void> {
|
||||
async function agentsList(instanceRoot?: string, json = false): Promise<void> {
|
||||
if (json) await muteForJson()
|
||||
const catalog = await createCatalog(instanceRoot);
|
||||
catalog.load();
|
||||
await catalog.refreshRegistryIfStale();
|
||||
|
||||
const items = catalog.getAvailable();
|
||||
|
||||
if (json) {
|
||||
jsonSuccess({
|
||||
agents: items.map((item) => ({
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
version: item.version,
|
||||
distribution: item.distribution,
|
||||
description: item.description ?? "",
|
||||
installed: item.installed,
|
||||
available: item.available ?? true,
|
||||
missingDeps: item.missingDeps ?? [],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const installed = items.filter((i) => i.installed);
|
||||
const available = items.filter((i) => !i.installed);
|
||||
|
||||
@ -126,8 +148,10 @@ async function agentsList(instanceRoot?: string): Promise<void> {
|
||||
console.log("");
|
||||
}
|
||||
|
||||
async function agentsInstall(nameOrId: string | undefined, force: boolean, help = false, instanceRoot?: string): Promise<void> {
|
||||
if (help || !nameOrId) {
|
||||
async function agentsInstall(nameOrId: string | undefined, force: boolean, help = false, instanceRoot?: string, json = false): Promise<void> {
|
||||
if (json) await muteForJson()
|
||||
|
||||
if (!json && (help || !nameOrId)) {
|
||||
console.log(`
|
||||
\x1b[1mopenacp agents install\x1b[0m — Install an agent from the ACP Registry
|
||||
|
||||
@ -139,6 +163,7 @@ async function agentsInstall(nameOrId: string | undefined, force: boolean, help
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--force Reinstall even if already installed
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
@ -150,11 +175,22 @@ Run 'openacp agents' to see available agents.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!nameOrId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Agent name is required')
|
||||
return
|
||||
}
|
||||
|
||||
const catalog = await createCatalog(instanceRoot);
|
||||
catalog.load();
|
||||
await catalog.refreshRegistryIfStale();
|
||||
|
||||
const progress: import("../../core/types.js").InstallProgress = {
|
||||
const progress: import("../../core/types.js").InstallProgress = json ? {
|
||||
onStart() {},
|
||||
onStep() {},
|
||||
onDownloadProgress() {},
|
||||
onSuccess() {},
|
||||
onError() {},
|
||||
} : {
|
||||
onStart(_id, name) {
|
||||
process.stdout.write(`\n ⏳ Installing ${name}...\n`);
|
||||
},
|
||||
@ -178,6 +214,7 @@ Run 'openacp agents' to see available agents.
|
||||
|
||||
const result = await catalog.install(nameOrId, progress, force);
|
||||
if (!result.ok) {
|
||||
if (json) jsonError(ErrorCodes.INSTALL_FAILED, result.error ?? 'Installation failed')
|
||||
if (result.error?.includes('not found')) {
|
||||
const { suggestMatch } = await import('../suggest.js');
|
||||
const allKeys = catalog.getAvailable().map((a) => a.key);
|
||||
@ -187,6 +224,11 @@ Run 'openacp agents' to see available agents.
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (json) {
|
||||
const installed = catalog.getInstalledAgent(result.agentKey)
|
||||
jsonSuccess({ key: result.agentKey, version: installed?.version ?? 'unknown', installed: true })
|
||||
}
|
||||
|
||||
// Auto-integrate handoff if agent supports it
|
||||
const { getAgentCapabilities } = await import("../../core/agents/agent-dependencies.js");
|
||||
const caps = getAgentCapabilities(result.agentKey);
|
||||
@ -210,8 +252,10 @@ Run 'openacp agents' to see available agents.
|
||||
}
|
||||
}
|
||||
|
||||
async function agentsUninstall(name: string | undefined, help = false, instanceRoot?: string): Promise<void> {
|
||||
if (help || !name) {
|
||||
async function agentsUninstall(name: string | undefined, help = false, instanceRoot?: string, json = false): Promise<void> {
|
||||
if (json) await muteForJson()
|
||||
|
||||
if (!json && (help || !name)) {
|
||||
console.log(`
|
||||
\x1b[1mopenacp agents uninstall\x1b[0m — Remove an installed agent
|
||||
|
||||
@ -221,12 +265,21 @@ async function agentsUninstall(name: string | undefined, help = false, instanceR
|
||||
\x1b[1mArguments:\x1b[0m
|
||||
<name> Agent name to remove
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
openacp agents uninstall gemini
|
||||
`)
|
||||
return;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Agent name is required')
|
||||
return
|
||||
}
|
||||
|
||||
const catalog = await createCatalog(instanceRoot);
|
||||
catalog.load();
|
||||
|
||||
@ -240,8 +293,10 @@ async function agentsUninstall(name: string | undefined, help = false, instanceR
|
||||
await uninstallIntegration(name, caps.integration);
|
||||
console.log(` \x1b[32m✓\x1b[0m Handoff integration removed for ${name}`);
|
||||
}
|
||||
if (json) jsonSuccess({ key: name, uninstalled: true })
|
||||
console.log(`\n \x1b[32m✓ ${name} removed.\x1b[0m\n`);
|
||||
} else {
|
||||
if (json) jsonError(ErrorCodes.UNINSTALL_FAILED, result.error ?? 'Uninstall failed')
|
||||
console.log(`\n \x1b[31m✗ ${result.error}\x1b[0m`);
|
||||
if (result.error?.includes('not installed')) {
|
||||
const { suggestMatch } = await import('../suggest.js');
|
||||
@ -261,8 +316,10 @@ async function agentsRefresh(instanceRoot?: string): Promise<void> {
|
||||
console.log(" \x1b[32m✓ Agent list updated.\x1b[0m\n");
|
||||
}
|
||||
|
||||
async function agentsInfo(nameOrId: string | undefined, help = false, instanceRoot?: string): Promise<void> {
|
||||
if (help || !nameOrId) {
|
||||
async function agentsInfo(nameOrId: string | undefined, help = false, instanceRoot?: string, json = false): Promise<void> {
|
||||
if (json) await muteForJson()
|
||||
|
||||
if (!json && (help || !nameOrId)) {
|
||||
console.log(`
|
||||
\x1b[1mopenacp agents info\x1b[0m — Show agent details, dependencies & setup guide
|
||||
|
||||
@ -275,6 +332,10 @@ async function agentsInfo(nameOrId: string | undefined, help = false, instanceRo
|
||||
Shows version, distribution type, command, setup steps, and
|
||||
whether the agent is installed or available from the registry.
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
openacp agents info claude
|
||||
openacp agents info cursor
|
||||
@ -282,6 +343,11 @@ whether the agent is installed or available from the registry.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!nameOrId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Agent name is required')
|
||||
return
|
||||
}
|
||||
|
||||
const catalog = await createCatalog(instanceRoot);
|
||||
catalog.load();
|
||||
|
||||
@ -289,6 +355,18 @@ whether the agent is installed or available from the registry.
|
||||
|
||||
const installed = catalog.getInstalledAgent(nameOrId);
|
||||
if (installed) {
|
||||
if (json) {
|
||||
jsonSuccess({
|
||||
key: installed.registryId ?? nameOrId,
|
||||
name: installed.name,
|
||||
version: installed.version,
|
||||
distribution: installed.distribution,
|
||||
installed: true,
|
||||
command: installed.command,
|
||||
binaryPath: installed.binaryPath ?? null,
|
||||
registryId: installed.registryId ?? null,
|
||||
})
|
||||
}
|
||||
console.log(`\n \x1b[1m${installed.name}\x1b[0m`);
|
||||
console.log(` Version: ${installed.version}`);
|
||||
console.log(` Type: ${installed.distribution}`);
|
||||
@ -311,6 +389,15 @@ whether the agent is installed or available from the registry.
|
||||
|
||||
const regAgent = catalog.findRegistryAgent(nameOrId);
|
||||
if (regAgent) {
|
||||
if (json) {
|
||||
jsonSuccess({
|
||||
key: regAgent.id,
|
||||
name: regAgent.name,
|
||||
version: regAgent.version,
|
||||
description: regAgent.description ?? '',
|
||||
installed: false,
|
||||
})
|
||||
}
|
||||
const availability = catalog.checkAvailability(nameOrId);
|
||||
console.log(`\n \x1b[1m${regAgent.name}\x1b[0m \x1b[2m(not installed)\x1b[0m`);
|
||||
console.log(` ${regAgent.description}`);
|
||||
@ -332,6 +419,7 @@ whether the agent is installed or available from the registry.
|
||||
return;
|
||||
}
|
||||
|
||||
if (json) jsonError(ErrorCodes.AGENT_NOT_FOUND, `"${nameOrId}" not found.`)
|
||||
const { suggestMatch } = await import('../suggest.js');
|
||||
const allKeys = catalog.getAvailable().map((a) => a.key);
|
||||
const suggestion = suggestMatch(nameOrId, allKeys);
|
||||
|
||||
@ -1,5 +1,25 @@
|
||||
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(`
|
||||
@ -42,6 +62,7 @@ function printApiHelp(): void {
|
||||
openacp api version Show daemon version
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
`)
|
||||
}
|
||||
@ -272,8 +293,12 @@ Shows the version of the currently running daemon process.
|
||||
return
|
||||
}
|
||||
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const port = readApiPort(undefined, instanceRoot)
|
||||
if (port === null) {
|
||||
if (json) jsonError(ErrorCodes.DAEMON_NOT_RUNNING, 'OpenACP is not running.')
|
||||
console.error('OpenACP is not running. Start with `openacp start`')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -299,9 +324,11 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log('Session created')
|
||||
console.log(` ID : ${data.sessionId}`)
|
||||
console.log(` Agent : ${data.agent}`)
|
||||
@ -313,6 +340,7 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'cancel') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api cancel <session-id>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -321,14 +349,17 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess({ cancelled: true, sessionId })
|
||||
console.log(`Session ${sessionId} cancelled`)
|
||||
|
||||
} else if (subCmd === 'status') {
|
||||
const res = await call('/api/sessions')
|
||||
const data = await res.json() as { sessions: Array<{ id: string; agent: string; status: string; name: string | null }> }
|
||||
if (json) jsonSuccess(data)
|
||||
if (data.sessions.length === 0) {
|
||||
console.log('No active sessions.')
|
||||
} else {
|
||||
@ -342,6 +373,7 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'agents') {
|
||||
const res = await call('/api/agents')
|
||||
const data = await res.json() as { agents: Array<{ name: string; command: string; args: string[] }>; default: string }
|
||||
if (json) jsonSuccess(data)
|
||||
console.log('Available agents:')
|
||||
for (const a of data.agents) {
|
||||
const isDefault = a.name === data.default ? ' (default)' : ''
|
||||
@ -354,6 +386,7 @@ Shows the version of the currently running daemon process.
|
||||
const query = statusParam ? `?status=${encodeURIComponent(statusParam)}` : ''
|
||||
const res = await call(`/api/topics${query}`)
|
||||
const data = await res.json() as { topics: Array<{ sessionId: string; topicId: number | null; name: string | null; status: string; agentName: string; lastActiveAt: string }> }
|
||||
if (json) jsonSuccess(data)
|
||||
if (data.topics.length === 0) {
|
||||
console.log('No topics found.')
|
||||
} else {
|
||||
@ -368,6 +401,7 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'delete-topic') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api delete-topic <session-id> [--force]')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -377,13 +411,16 @@ Shows the version of the currently running daemon process.
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (res.status === 409) {
|
||||
const session = data.session as Record<string, unknown> | undefined
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, `Session "${sessionId}" is active (${session?.status}). Use --force to delete.`)
|
||||
console.error(`Session "${sessionId}" is active (${session?.status}). Use --force to delete.`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const topicLabel = data.topicId ? `Topic #${data.topicId}` : 'headless session'
|
||||
console.log(`${topicLabel} deleted (session ${sessionId})`)
|
||||
|
||||
@ -398,6 +435,7 @@ Shows the version of the currently running daemon process.
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const data = await res.json() as { deleted: string[]; failed: Array<{ sessionId: string; error: string }> }
|
||||
if (json) jsonSuccess(data)
|
||||
if (data.deleted.length === 0 && data.failed.length === 0) {
|
||||
console.log('Nothing to clean up.')
|
||||
} else {
|
||||
@ -410,11 +448,13 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'send') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api send <session-id> <prompt>')
|
||||
process.exit(1)
|
||||
}
|
||||
const prompt = args.slice(2).join(' ')
|
||||
if (!prompt) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Prompt is required')
|
||||
console.error('Usage: openacp api send <session-id> <prompt>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -425,23 +465,28 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log(`Prompt sent to session ${sessionId} (queue depth: ${data.queueDepth})`)
|
||||
|
||||
} else if (subCmd === 'session') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api session <session-id>')
|
||||
process.exit(1)
|
||||
}
|
||||
const res = await call(`/api/sessions/${encodeURIComponent(sessionId)}`)
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const s = (data.session ?? data) as Record<string, unknown>
|
||||
console.log(`Session details:`)
|
||||
console.log(` ID : ${s.id}`)
|
||||
@ -459,11 +504,13 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'dangerous' || subCmd === 'bypass') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api bypass <session-id> [on|off]')
|
||||
process.exit(1)
|
||||
}
|
||||
const toggle = args[2]
|
||||
if (!toggle || (toggle !== 'on' && toggle !== 'off')) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Toggle value (on|off) is required')
|
||||
console.error('Usage: openacp api bypass <session-id> [on|off]')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -474,9 +521,11 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const state = toggle === 'on' ? 'enabled' : 'disabled'
|
||||
console.log(`Bypass permissions ${state} for session ${sessionId}`)
|
||||
|
||||
@ -484,9 +533,11 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const uptimeMs = typeof data.uptime === 'number' ? data.uptime : 0
|
||||
const uptimeSeconds = Math.floor(uptimeMs / 1000)
|
||||
const hours = Math.floor(uptimeSeconds / 3600)
|
||||
@ -509,9 +560,11 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess({ restarted: true })
|
||||
console.log('Restart signal sent. OpenACP is restarting...')
|
||||
|
||||
} else if (subCmd === 'config') {
|
||||
@ -521,14 +574,17 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log(JSON.stringify(data.config, null, 2))
|
||||
} else if (subSubCmd === 'set') {
|
||||
const configPath = args[2]
|
||||
const configValue = args[3]
|
||||
if (!configPath || configValue === undefined) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Config path and value are required')
|
||||
console.error('Usage: openacp api config set <path> <value>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -545,14 +601,17 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log(`Config updated: ${configPath} = ${JSON.stringify(value)}`)
|
||||
if (data.needsRestart) {
|
||||
console.log('Note: restart required for this change to take effect.')
|
||||
}
|
||||
} else {
|
||||
if (json) jsonError(ErrorCodes.UNKNOWN_COMMAND, `Unknown config subcommand: ${subSubCmd}`)
|
||||
console.error(`Unknown config subcommand: ${subSubCmd}`)
|
||||
console.log(' openacp api config Show runtime config')
|
||||
console.log(' openacp api config set <key> <value> Update config value')
|
||||
@ -563,9 +622,11 @@ Shows the version of the currently running daemon process.
|
||||
const res = await call('/api/adapters')
|
||||
const data = await res.json() as { adapters: Array<{ name: string; type: string }> }
|
||||
if (!res.ok) {
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, String((data as Record<string, unknown>).error ?? 'API request failed'))
|
||||
console.error(`Error: ${(data as Record<string, unknown>).error}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log('Registered adapters:')
|
||||
for (const a of data.adapters) {
|
||||
console.log(` ${a.name} (${a.type})`)
|
||||
@ -575,9 +636,11 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
if (data.enabled) {
|
||||
console.log(`Tunnel provider : ${data.provider}`)
|
||||
console.log(`Tunnel URL : ${data.url}`)
|
||||
@ -588,6 +651,7 @@ Shows the version of the currently running daemon process.
|
||||
} else if (subCmd === 'notify') {
|
||||
const message = args.slice(1).join(' ')
|
||||
if (!message) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Message is required')
|
||||
console.error('Usage: openacp api notify <message>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -598,23 +662,28 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess({ sent: true })
|
||||
console.log('Notification sent to all channels.')
|
||||
|
||||
} else if (subCmd === 'version') {
|
||||
const res = await call('/api/version')
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log(`Daemon version: ${data.version}`)
|
||||
|
||||
} else if (subCmd === 'session-config') {
|
||||
const sessionId = args[1]
|
||||
if (!sessionId) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Session ID is required')
|
||||
console.error('Usage: openacp api session-config <session-id> [set <opt> <value> | overrides | dangerous [on|off]]')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -625,9 +694,11 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const configOptions = data.configOptions as Array<Record<string, unknown>> | undefined
|
||||
const clientOverrides = data.clientOverrides as Record<string, unknown> | undefined
|
||||
if (!configOptions || configOptions.length === 0) {
|
||||
@ -660,6 +731,7 @@ Shows the version of the currently running daemon process.
|
||||
const configId = args[3]
|
||||
const value = args[4]
|
||||
if (!configId || value === undefined) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Config ID and value are required')
|
||||
console.error('Usage: openacp api session-config <session-id> set <config-id> <value>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -670,9 +742,11 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
console.log(`Config option "${configId}" updated to "${value}"`)
|
||||
const configOptions = data.configOptions as Array<Record<string, unknown>> | undefined
|
||||
const updated = configOptions?.find((o) => o.id === configId)
|
||||
@ -685,9 +759,11 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const overrides = data.clientOverrides as Record<string, unknown> | undefined
|
||||
if (!overrides || Object.keys(overrides).length === 0) {
|
||||
console.log('No client overrides set.')
|
||||
@ -701,6 +777,7 @@ Shows the version of the currently running daemon process.
|
||||
} else if (configSubCmd === 'dangerous') {
|
||||
const toggle = args[3]
|
||||
if (toggle && toggle !== 'on' && toggle !== 'off') {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Toggle value must be on or off')
|
||||
console.error('Usage: openacp api session-config <session-id> dangerous [on|off]')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -713,9 +790,11 @@ Shows the version of the currently running daemon process.
|
||||
})
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const state = toggle === 'on' ? 'enabled' : 'disabled'
|
||||
console.log(`bypassPermissions ${state} for session ${sessionId}`)
|
||||
} else {
|
||||
@ -723,15 +802,18 @@ 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) {
|
||||
console.error(`Error: ${data.error}`)
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, extractApiError(data))
|
||||
console.error(`Error: ${extractApiError(data)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess(data)
|
||||
const overrides = data.clientOverrides as Record<string, unknown> | undefined
|
||||
const bypass = overrides?.bypassPermissions
|
||||
console.log(`bypassPermissions: ${bypass ?? false}`)
|
||||
}
|
||||
|
||||
} else {
|
||||
if (json) jsonError(ErrorCodes.UNKNOWN_COMMAND, `Unknown session-config subcommand: ${configSubCmd}`)
|
||||
console.error(`Unknown session-config subcommand: ${configSubCmd}`)
|
||||
console.log(' openacp api session-config <id> List config options')
|
||||
console.log(' openacp api session-config <id> set <opt> <value> Set a config option')
|
||||
@ -748,17 +830,22 @@ Shows the version of the currently running daemon process.
|
||||
'config', 'adapters', 'tunnel', 'notify', 'version', 'session-config',
|
||||
]
|
||||
const suggestion = suggestMatch(subCmd ?? '', apiSubcommands)
|
||||
if (json) jsonError(ErrorCodes.UNKNOWN_COMMAND, `Unknown api command: ${subCmd || '(none)'}`)
|
||||
console.error(`Unknown api command: ${subCmd || '(none)'}\n`)
|
||||
if (suggestion) console.error(`Did you mean: ${suggestion}?\n`)
|
||||
printApiHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
} catch (err) {
|
||||
// jsonSuccess/jsonError call process.exit which may throw in certain environments
|
||||
if (err instanceof Error && err.message.startsWith('process.exit')) throw err
|
||||
if (err instanceof TypeError && (err.cause as Record<string, unknown> | undefined)?.code === 'ECONNREFUSED') {
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, 'OpenACP is not running (stale port file)')
|
||||
console.error('OpenACP is not running (stale port file)')
|
||||
removeStalePortFile(undefined, instanceRoot)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, (err as Error).message)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import * as pathMod from 'node:path'
|
||||
import { readApiPort, apiCall } from '../api-client.js'
|
||||
import { wantsHelp, buildNestedUpdateFromPath } from './helpers.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
|
||||
export async function cmdConfig(args: string[] = [], instanceRoot?: string): Promise<void> {
|
||||
const subCmd = args[0] // 'set' or undefined
|
||||
@ -17,6 +18,7 @@ export async function cmdConfig(args: string[] = [], instanceRoot?: string): Pro
|
||||
<value> New value (JSON-parsed if possible, otherwise string)
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
Works with both running and stopped daemon. When running, uses
|
||||
@ -39,6 +41,7 @@ the API for live updates. When stopped, edits config file directly.
|
||||
openacp config set <key> <value> Set a config value directly
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
Works with both running and stopped daemon. When running, uses
|
||||
@ -55,9 +58,13 @@ the API for live updates. When stopped, edits config file directly.
|
||||
|
||||
if (subCmd === 'set') {
|
||||
// Non-interactive: openacp config set <key> <value>
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const configPath = args[1]
|
||||
const configValue = args[2]
|
||||
if (!configPath || configValue === undefined) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Missing required arguments: <path> and <value>')
|
||||
console.error('Usage: openacp config set <path> <value>')
|
||||
process.exit(1)
|
||||
}
|
||||
@ -67,6 +74,7 @@ the API for live updates. When stopped, edits config file directly.
|
||||
const topLevelKey = configPath.split('.')[0]
|
||||
const validConfigKeys = Object.keys(ConfigSchema.shape)
|
||||
if (!validConfigKeys.includes(topLevelKey)) {
|
||||
if (json) jsonError(ErrorCodes.CONFIG_INVALID, `Unknown config key: ${topLevelKey}`)
|
||||
const { suggestMatch } = await import('../suggest.js')
|
||||
const suggestion = suggestMatch(topLevelKey, validConfigKeys)
|
||||
console.error(`Unknown config key: ${topLevelKey}`)
|
||||
@ -87,9 +95,11 @@ the API for live updates. When stopped, edits config file directly.
|
||||
}, instanceRoot)
|
||||
const data = await res.json() as Record<string, unknown>
|
||||
if (!res.ok) {
|
||||
if (json) jsonError(ErrorCodes.API_ERROR, `${data.error}`)
|
||||
console.error(`Error: ${data.error}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess({ path: configPath, value, needsRestart: data.needsRestart ?? false })
|
||||
console.log(`Config updated: ${configPath} = ${JSON.stringify(value)}`)
|
||||
if (data.needsRestart) {
|
||||
console.log('Note: restart required for this change to take effect.')
|
||||
@ -99,12 +109,14 @@ the API for live updates. When stopped, edits config file directly.
|
||||
const { ConfigManager } = await import('../../core/config/config.js')
|
||||
const cm = new ConfigManager(instanceRoot ? pathMod.join(instanceRoot, 'config.json') : undefined)
|
||||
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.')
|
||||
process.exit(1)
|
||||
}
|
||||
await cm.load()
|
||||
const updates = buildNestedUpdateFromPath(configPath, value)
|
||||
await cm.save(updates)
|
||||
if (json) jsonSuccess({ path: configPath, value, needsRestart: false })
|
||||
console.log(`Config updated: ${configPath} = ${JSON.stringify(value)}`)
|
||||
}
|
||||
return
|
||||
@ -113,16 +125,21 @@ the API for live updates. When stopped, edits config file directly.
|
||||
// Interactive editor
|
||||
const { runConfigEditor } = await import('../../core/config/config-editor.js')
|
||||
const { ConfigManager } = await import('../../core/config/config.js')
|
||||
const { SettingsManager } = await import('../../core/plugin/settings-manager.js')
|
||||
const { getGlobalRoot } = await import('../../core/instance/instance-context.js')
|
||||
const cm = new ConfigManager(instanceRoot ? pathMod.join(instanceRoot, 'config.json') : undefined)
|
||||
if (!(await cm.exists())) {
|
||||
console.error('No config found. Run "openacp" first to set up.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const root = instanceRoot ?? getGlobalRoot()
|
||||
const settingsManager = new SettingsManager(pathMod.join(root, 'plugins', 'data'))
|
||||
|
||||
const port = readApiPort(undefined, instanceRoot)
|
||||
if (port !== null) {
|
||||
await runConfigEditor(cm, 'api', port)
|
||||
await runConfigEditor(cm, 'api', port, settingsManager)
|
||||
} else {
|
||||
await runConfigEditor(cm, 'file')
|
||||
await runConfigEditor(cm, 'file', undefined, settingsManager)
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,10 +2,18 @@ import { checkAndPromptUpdate } from '../version.js'
|
||||
import { printHelp } from './help.js'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import fs from 'node:fs'
|
||||
import { createInstanceContext, getGlobalRoot } from '../../core/instance/instance-context.js'
|
||||
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { printInstanceHint } from '../instance-hint.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
|
||||
export async function cmdDefault(command: string | undefined, instanceRoot?: string): Promise<void> {
|
||||
const args = command ? [command] : []
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
|
||||
const pluginsDataDir = path.join(root, 'plugins', 'data')
|
||||
const registryPath = path.join(root, 'plugins.json')
|
||||
@ -60,9 +68,36 @@ export async function cmdDefault(command: string | undefined, instanceRoot?: str
|
||||
|
||||
const result = startDaemon(pidPath, config.logging.logDir, root)
|
||||
if ('error' in result) {
|
||||
if (json) jsonError(ErrorCodes.DAEMON_NOT_RUNNING, result.error)
|
||||
console.error(result.error)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) {
|
||||
// Resolve instanceId from registry if available
|
||||
let instanceId: string = path.basename(root)
|
||||
try {
|
||||
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
|
||||
reg.load()
|
||||
const entry = reg.getByRoot(root)
|
||||
if (entry) instanceId = entry.id
|
||||
} catch {}
|
||||
// Try to read actual port from api.port file written by the server after startup
|
||||
let port: number | null = null
|
||||
try {
|
||||
const portStr = fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()
|
||||
port = parseInt(portStr) || null
|
||||
} catch {
|
||||
port = 21420
|
||||
}
|
||||
jsonSuccess({
|
||||
pid: result.pid,
|
||||
instanceId,
|
||||
name: config.instanceName ?? null,
|
||||
directory: path.dirname(root),
|
||||
dir: root,
|
||||
port,
|
||||
})
|
||||
}
|
||||
printInstanceHint(root)
|
||||
console.log(`OpenACP daemon started (PID ${result.pid})`)
|
||||
return
|
||||
@ -72,11 +107,35 @@ export async function cmdDefault(command: string | undefined, instanceRoot?: str
|
||||
markRunning(root)
|
||||
printInstanceHint(root)
|
||||
const { startServer } = await import('../../main.js')
|
||||
const reg = new InstanceRegistry(path.join(getGlobalRoot(), 'instances.json'))
|
||||
reg.load()
|
||||
const existingEntry = reg.getByRoot(root)
|
||||
const instanceId = existingEntry?.id ?? randomUUID()
|
||||
const ctx = createInstanceContext({
|
||||
id: 'default',
|
||||
id: instanceId,
|
||||
root,
|
||||
isGlobal: root === getGlobalRoot(),
|
||||
})
|
||||
|
||||
if (json) {
|
||||
// For foreground mode, output JSON before starting the server
|
||||
let port: number | null = null
|
||||
try {
|
||||
const portStr = fs.readFileSync(path.join(root, 'api.port'), 'utf-8').trim()
|
||||
port = parseInt(portStr) || null
|
||||
} catch {
|
||||
port = 21420
|
||||
}
|
||||
jsonSuccess({
|
||||
pid: process.pid,
|
||||
instanceId,
|
||||
name: config.instanceName ?? null,
|
||||
directory: path.dirname(root),
|
||||
dir: root,
|
||||
port,
|
||||
})
|
||||
}
|
||||
|
||||
await startServer({ instanceContext: ctx })
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
import { wantsHelp } from './helpers.js'
|
||||
import { isJsonMode, jsonSuccess, muteForJson } from '../output.js'
|
||||
|
||||
export async function cmdDoctor(args: string[], instanceRoot?: string): Promise<void> {
|
||||
if (wantsHelp(args)) {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
if (!json && wantsHelp(args)) {
|
||||
console.log(`
|
||||
\x1b[1mopenacp doctor\x1b[0m — Run system diagnostics
|
||||
|
||||
@ -10,6 +14,7 @@ export async function cmdDoctor(args: string[], instanceRoot?: string): Promise<
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--dry-run Check only, don't apply any fixes
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
Checks your OpenACP installation for common issues including
|
||||
@ -19,11 +24,11 @@ Fixable issues can be auto-repaired when not using --dry-run.
|
||||
return
|
||||
}
|
||||
|
||||
const knownFlags = ["--dry-run"];
|
||||
const knownFlags = ["--dry-run", "--json"];
|
||||
const unknownFlags = args.filter(
|
||||
(a) => a.startsWith("--") && !knownFlags.includes(a),
|
||||
);
|
||||
if (unknownFlags.length > 0) {
|
||||
if (!json && unknownFlags.length > 0) {
|
||||
const { suggestMatch } = await import('../suggest.js');
|
||||
for (const flag of unknownFlags) {
|
||||
const suggestion = suggestMatch(flag, knownFlags);
|
||||
@ -33,14 +38,29 @@ Fixable issues can be auto-repaired when not using --dry-run.
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const dryRun = args.includes("--dry-run");
|
||||
// --json implies --dry-run
|
||||
const dryRun = args.includes("--dry-run") || json;
|
||||
const { DoctorEngine } = await import("../../core/doctor/index.js");
|
||||
const engine = new DoctorEngine({ dryRun, dataDir: instanceRoot });
|
||||
|
||||
console.log("\n🩺 OpenACP Doctor\n");
|
||||
if (!json) console.log("\n🩺 OpenACP Doctor\n");
|
||||
|
||||
const report = await engine.runAll();
|
||||
|
||||
if (json) {
|
||||
jsonSuccess({
|
||||
categories: report.categories.map((c) => ({
|
||||
name: c.name,
|
||||
results: c.results.map((r) => ({ status: r.status, message: r.message })),
|
||||
})),
|
||||
summary: {
|
||||
passed: report.summary.passed,
|
||||
warnings: report.summary.warnings,
|
||||
failed: report.summary.failed,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Render results
|
||||
const icons = { pass: "\x1b[32m✅\x1b[0m", warn: "\x1b[33m⚠️\x1b[0m", fail: "\x1b[31m❌\x1b[0m" };
|
||||
|
||||
|
||||
@ -9,21 +9,21 @@ Connect messaging platforms (Telegram, Discord) to 28+ AI coding agents via ACP
|
||||
|
||||
\x1b[1mServer:\x1b[0m
|
||||
openacp Start (mode from config)
|
||||
openacp start Start as background daemon
|
||||
openacp stop Stop background daemon
|
||||
openacp restart Restart (same mode)
|
||||
openacp start Start as background daemon \x1b[2m[--json]\x1b[0m
|
||||
openacp stop Stop background daemon \x1b[2m[--json]\x1b[0m
|
||||
openacp restart Restart (same mode) \x1b[2m[--json]\x1b[0m
|
||||
openacp restart --foreground Restart in foreground mode
|
||||
openacp restart --daemon Restart as background daemon
|
||||
openacp attach Attach to running daemon
|
||||
openacp status Show daemon status
|
||||
openacp status Show daemon status \x1b[2m[--json]\x1b[0m
|
||||
openacp logs Tail daemon log file
|
||||
openacp --foreground Force foreground mode
|
||||
|
||||
\x1b[1mAgent Management:\x1b[0m
|
||||
openacp agents Browse all agents (installed + available)
|
||||
openacp agents install <name> Install an agent from the ACP Registry
|
||||
openacp agents uninstall <name> Remove an installed agent
|
||||
openacp agents info <name> Show details, dependencies & setup guide
|
||||
openacp agents Browse all agents (installed + available) \x1b[2m[--json]\x1b[0m
|
||||
openacp agents install <name> Install an agent from the ACP Registry \x1b[2m[--json]\x1b[0m
|
||||
openacp agents uninstall <name> Remove an installed agent \x1b[2m[--json]\x1b[0m
|
||||
openacp agents info <name> Show details, dependencies & setup guide \x1b[2m[--json]\x1b[0m
|
||||
openacp agents run <name> [-- args] Run agent CLI directly (login, config...)
|
||||
openacp agents refresh Force-refresh agent list from registry
|
||||
|
||||
@ -34,17 +34,17 @@ Connect messaging platforms (Telegram, Discord) to 28+ AI coding agents via ACP
|
||||
|
||||
\x1b[1mConfiguration:\x1b[0m
|
||||
openacp config Interactive config editor
|
||||
openacp config set <key> <value> Set a config value
|
||||
openacp config set <key> <value> Set a config value \x1b[2m[--json]\x1b[0m
|
||||
openacp onboard Re-run onboarding setup wizard
|
||||
openacp reset Re-run setup wizard
|
||||
openacp update Update to latest version
|
||||
openacp doctor Run system diagnostics
|
||||
openacp doctor Run system diagnostics \x1b[2m[--json]\x1b[0m
|
||||
openacp doctor --dry-run Check only, don't fix
|
||||
|
||||
\x1b[1mPlugins:\x1b[0m
|
||||
openacp install <package> Install adapter plugin
|
||||
openacp uninstall <package> Remove adapter
|
||||
openacp plugins List installed plugins
|
||||
openacp install <package> Install adapter plugin \x1b[2m[--json]\x1b[0m
|
||||
openacp uninstall <package> Remove adapter \x1b[2m[--json]\x1b[0m
|
||||
openacp plugins List installed plugins \x1b[2m[--json]\x1b[0m
|
||||
openacp plugin create Scaffold a new plugin project
|
||||
|
||||
\x1b[1mDevelopment:\x1b[0m
|
||||
@ -55,25 +55,33 @@ Connect messaging platforms (Telegram, Discord) to 28+ AI coding agents via ACP
|
||||
\x1b[1mSession Transfer:\x1b[0m
|
||||
openacp integrate <agent> Install handoff integration
|
||||
openacp integrate <agent> --uninstall
|
||||
openacp adopt <agent> <id> Adopt an external session
|
||||
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
|
||||
openacp tunnel list List active tunnels
|
||||
openacp tunnel stop <port> Stop a tunnel
|
||||
openacp tunnel stop-all Stop all user tunnels
|
||||
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
|
||||
openacp tunnel stop <port> Stop a tunnel \x1b[2m[--json]\x1b[0m
|
||||
openacp tunnel stop-all Stop all user tunnels \x1b[2m[--json]\x1b[0m
|
||||
|
||||
\x1b[1mDaemon API:\x1b[0m \x1b[2m(requires running daemon)\x1b[0m
|
||||
openacp api status Active sessions
|
||||
openacp api session <id> Session details
|
||||
openacp api new [agent] [workspace] Create session
|
||||
openacp api send <id> <prompt> Send prompt
|
||||
openacp api cancel <id> Cancel session
|
||||
openacp api bypass <id> on|off Toggle bypass permissions
|
||||
openacp api topics [--status ...] List topics
|
||||
openacp api cleanup [--status ...] Cleanup old topics
|
||||
openacp api health System health check
|
||||
openacp api restart Restart daemon
|
||||
openacp api status Active sessions \x1b[2m[--json]\x1b[0m
|
||||
openacp api session <id> Session details \x1b[2m[--json]\x1b[0m
|
||||
openacp api new [agent] [workspace] Create session \x1b[2m[--json]\x1b[0m
|
||||
openacp api send <id> <prompt> Send prompt \x1b[2m[--json]\x1b[0m
|
||||
openacp api cancel <id> Cancel session \x1b[2m[--json]\x1b[0m
|
||||
openacp api bypass <id> on|off Toggle bypass permissions \x1b[2m[--json]\x1b[0m
|
||||
openacp api topics [--status ...] List topics \x1b[2m[--json]\x1b[0m
|
||||
openacp api cleanup [--status ...] Cleanup old topics \x1b[2m[--json]\x1b[0m
|
||||
openacp api health System health check \x1b[2m[--json]\x1b[0m
|
||||
openacp api restart Restart daemon \x1b[2m[--json]\x1b[0m
|
||||
|
||||
\x1b[1mWorkspace Flags:\x1b[0m
|
||||
--local Use workspace in current directory
|
||||
@ -82,6 +90,12 @@ Connect messaging platforms (Telegram, Discord) to 28+ AI coding agents via ACP
|
||||
--from <path> Copy settings from existing workspace (on create)
|
||||
--name <name> Set workspace name (on create)
|
||||
|
||||
\x1b[1mOutput Flags:\x1b[0m
|
||||
--json Output result as JSON (single-line, stdout)
|
||||
Commands marked \x1b[2m[--json]\x1b[0m support machine-readable output.
|
||||
Success: { "success": true, "data": { ... } }
|
||||
Error: { "success": false, "error": { "code": "...", "message": "..." } }
|
||||
|
||||
\x1b[2mMore info: https://github.com/Open-ACP/OpenACP\x1b[0m
|
||||
`)
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ export { cmdConfig } from './config.js'
|
||||
export { cmdReset } from './reset.js'
|
||||
export { cmdUpdate } from './update.js'
|
||||
export { cmdAdopt } from './adopt.js'
|
||||
export { cmdInstances } from './instances.js'
|
||||
export { cmdIntegrate } from './integrate.js'
|
||||
export { cmdDoctor } from './doctor.js'
|
||||
export { cmdAgents } from './agents.js'
|
||||
@ -22,3 +23,4 @@ export { cmdDefault } from './default.js'
|
||||
export { cmdDev } from './dev.js'
|
||||
export { cmdAttach } from './attach.js'
|
||||
export { cmdRemote } from './remote.js'
|
||||
export { cmdSetup } from './setup.js'
|
||||
|
||||
@ -3,11 +3,16 @@ import * as fs from 'node:fs'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
import { wantsHelp } from './helpers.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
|
||||
export async function cmdInstall(args: string[], instanceRoot?: string): Promise<void> {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const root = instanceRoot ?? path.join(os.homedir(), '.openacp')
|
||||
const pluginsDir = path.join(root, 'plugins')
|
||||
if (wantsHelp(args)) {
|
||||
|
||||
if (!json && wantsHelp(args)) {
|
||||
console.log(`
|
||||
\x1b[1mopenacp install\x1b[0m — Install a plugin adapter
|
||||
|
||||
@ -15,26 +20,40 @@ export async function cmdInstall(args: string[], instanceRoot?: string): Promise
|
||||
openacp install <package>
|
||||
|
||||
\x1b[1mArguments:\x1b[0m
|
||||
<package> npm package name (e.g. @openacp/adapter-discord)
|
||||
<package> npm package name (e.g. @openacp/discord-adapter)
|
||||
|
||||
Installs the plugin to ~/.openacp/plugins/.
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output result as JSON
|
||||
-h, --help Show this help message
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
openacp install @openacp/adapter-discord
|
||||
openacp install @openacp/discord-adapter
|
||||
`)
|
||||
return
|
||||
}
|
||||
const pkg = args[0]
|
||||
|
||||
const pkg = args.filter(a => a !== '--json')[0]
|
||||
if (!pkg) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, 'Package name is required')
|
||||
console.error("Usage: openacp install <package>")
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
fs.mkdirSync(pluginsDir, { recursive: true })
|
||||
const pkgPath = path.join(pluginsDir, 'package.json')
|
||||
if (!fs.existsSync(pkgPath)) {
|
||||
fs.writeFileSync(pkgPath, JSON.stringify({ name: 'openacp-plugins', private: true, dependencies: {} }, null, 2))
|
||||
}
|
||||
console.log(`Installing ${pkg}...`)
|
||||
execSync(`npm install ${pkg} --prefix "${pluginsDir}"`, { stdio: 'inherit' })
|
||||
|
||||
if (!json) console.log(`Installing ${pkg}...`)
|
||||
try {
|
||||
execSync(`npm install ${pkg} --prefix "${pluginsDir}"`, { stdio: json ? 'pipe' : 'inherit' })
|
||||
} catch (err) {
|
||||
if (json) jsonError(ErrorCodes.INSTALL_FAILED, `Failed to install ${pkg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (json) jsonSuccess({ plugin: pkg, installed: true })
|
||||
console.log(`Plugin ${pkg} installed successfully.`)
|
||||
}
|
||||
|
||||
225
src/cli/commands/instances.ts
Normal file
225
src/cli/commands/instances.ts
Normal file
@ -0,0 +1,225 @@
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import fs from 'node:fs'
|
||||
import { InstanceRegistry } from '../../core/instance/instance-registry.js'
|
||||
import { getGlobalRoot, generateSlug } from '../../core/instance/instance-context.js'
|
||||
import { readInstanceInfo } from './status.js'
|
||||
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
|
||||
import { wantsHelp } from './helpers.js'
|
||||
|
||||
export interface InstanceListEntry {
|
||||
id: string
|
||||
name: string | null
|
||||
directory: string
|
||||
root: string
|
||||
status: 'running' | 'stopped'
|
||||
port: number | null
|
||||
}
|
||||
|
||||
export async function buildInstanceListEntries(): Promise<InstanceListEntry[]> {
|
||||
const registryPath = path.join(getGlobalRoot(), 'instances.json')
|
||||
const registry = new InstanceRegistry(registryPath)
|
||||
registry.load()
|
||||
return registry.list().map(entry => {
|
||||
const info = readInstanceInfo(entry.root)
|
||||
return {
|
||||
id: entry.id,
|
||||
name: info.name,
|
||||
directory: path.dirname(entry.root),
|
||||
root: entry.root,
|
||||
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
|
||||
port: info.apiPort,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function cmdInstances(args: string[] = [], parentFlags?: { dir?: string; from?: string; name?: string }): Promise<void> {
|
||||
if (wantsHelp(args)) {
|
||||
printInstancesHelp()
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
console.error(`Unknown subcommand: instances ${sub}`)
|
||||
printInstancesHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
function printInstancesHelp(): void {
|
||||
console.log(`
|
||||
\x1b[1mopenacp instances\x1b[0m — Manage OpenACP instances
|
||||
|
||||
\x1b[1mSubcommands:\x1b[0m
|
||||
list List all registered instances
|
||||
create Create or register an instance
|
||||
|
||||
\x1b[1mOptions:\x1b[0m
|
||||
--json Output as JSON
|
||||
`)
|
||||
}
|
||||
|
||||
async function cmdInstancesList(args: string[]): Promise<void> {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
const entries = await buildInstanceListEntries()
|
||||
|
||||
if (json) {
|
||||
jsonSuccess(entries)
|
||||
return
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
console.log('No instances registered.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(' Status ID Name Directory')
|
||||
console.log(' ' + '─'.repeat(70))
|
||||
for (const e of entries) {
|
||||
const status = e.status === 'running' ? '● running' : '○ stopped'
|
||||
const port = e.port ? `:${e.port}` : '—'
|
||||
const dir = e.directory.replace(os.homedir(), '~')
|
||||
const name = (e.name ?? e.id).padEnd(16)
|
||||
console.log(` ${status.padEnd(10)} ${e.id.padEnd(16)} ${name} ${dir} ${port}`)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
|
||||
export async function cmdInstancesCreate(args: string[]): Promise<void> {
|
||||
const json = isJsonMode(args)
|
||||
if (json) await muteForJson()
|
||||
|
||||
// Parse flags
|
||||
const dirIdx = args.indexOf('--dir')
|
||||
const rawDir = dirIdx !== -1 ? args[dirIdx + 1] : undefined
|
||||
if (!rawDir) {
|
||||
if (json) jsonError(ErrorCodes.MISSING_ARGUMENT, '--dir is required')
|
||||
console.error('Error: --dir is required')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const fromIdx = args.indexOf('--from')
|
||||
const rawFrom = fromIdx !== -1 ? args[fromIdx + 1] : undefined
|
||||
const nameIdx = args.indexOf('--name')
|
||||
const instanceName = nameIdx !== -1 ? args[nameIdx + 1] : undefined
|
||||
const agentIdx = args.indexOf('--agent')
|
||||
const agent = agentIdx !== -1 ? args[agentIdx + 1] : undefined
|
||||
const noInteractive = args.includes('--no-interactive')
|
||||
|
||||
// Resolve absolute paths
|
||||
const resolvedDir = path.resolve(rawDir.replace(/^~/, os.homedir()))
|
||||
const instanceRoot = path.join(resolvedDir, '.openacp')
|
||||
|
||||
const registryPath = path.join(getGlobalRoot(), 'instances.json')
|
||||
const registry = new InstanceRegistry(registryPath)
|
||||
registry.load()
|
||||
|
||||
// Case: .openacp already exists
|
||||
if (fs.existsSync(instanceRoot)) {
|
||||
const existing = registry.getByRoot(instanceRoot)
|
||||
if (existing) {
|
||||
if (json) jsonError(ErrorCodes.UNKNOWN_ERROR, `Instance already exists at ${resolvedDir} (id: ${existing.id})`)
|
||||
console.error(`Error: Instance already exists at ${resolvedDir} (id: ${existing.id})`)
|
||||
process.exit(1)
|
||||
}
|
||||
// .openacp exists but not registered — register it
|
||||
const configPath = path.join(instanceRoot, 'config.json')
|
||||
let name = path.basename(resolvedDir)
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
|
||||
name = config.instanceName ?? name
|
||||
} catch {}
|
||||
const id = registry.uniqueId(generateSlug(name))
|
||||
registry.register(id, instanceRoot)
|
||||
registry.save()
|
||||
await outputInstance(json, { id, root: instanceRoot })
|
||||
return
|
||||
}
|
||||
|
||||
// Case: create new
|
||||
const name = instanceName ?? `openacp-${registry.list().length + 1}`
|
||||
const id = registry.uniqueId(generateSlug(name))
|
||||
|
||||
if (rawFrom) {
|
||||
// Clone from existing instance using copyInstance
|
||||
const fromRoot = path.join(path.resolve(rawFrom.replace(/^~/, os.homedir())), '.openacp')
|
||||
if (!fs.existsSync(path.join(fromRoot, 'config.json'))) {
|
||||
console.error(`Error: No OpenACP instance found at ${rawFrom}`)
|
||||
process.exit(1)
|
||||
}
|
||||
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
|
||||
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,
|
||||
}
|
||||
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,
|
||||
}
|
||||
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.`)
|
||||
}
|
||||
|
||||
registry.register(id, instanceRoot)
|
||||
registry.save()
|
||||
await outputInstance(json, { id, root: instanceRoot })
|
||||
}
|
||||
|
||||
async function outputInstance(json: boolean, { id, root }: { id: string; root: string }): Promise<void> {
|
||||
const info = readInstanceInfo(root)
|
||||
const entry: InstanceListEntry = {
|
||||
id,
|
||||
name: info.name,
|
||||
directory: path.dirname(root),
|
||||
root,
|
||||
status: (info.pid ? 'running' : 'stopped') as 'running' | 'stopped',
|
||||
port: info.apiPort,
|
||||
}
|
||||
if (json) {
|
||||
jsonSuccess(entry)
|
||||
return
|
||||
}
|
||||
console.log(`Instance created: ${info.name ?? id} at ${path.dirname(root)}`)
|
||||
}
|
||||
@ -17,11 +17,12 @@ 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, the Claude integration adds
|
||||
a "Handoff" slash command to Claude Code.
|
||||
to OpenACP (Telegram/Discord). For example, integrations add an
|
||||
agent-native handoff command such as /openacp:handoff.
|
||||
|
||||
\x1b[1mExamples:\x1b[0m
|
||||
openacp integrate claude
|
||||
openacp integrate opencode
|
||||
openacp integrate claude --uninstall
|
||||
`)
|
||||
return
|
||||
|
||||
@ -17,7 +17,7 @@ export async function cmdOnboard(instanceRoot?: string): Promise<void> {
|
||||
|
||||
if (await cm.exists()) {
|
||||
const { runReconfigure } = await import('../../core/setup/index.js')
|
||||
await runReconfigure(cm)
|
||||
await runReconfigure(cm, settingsManager)
|
||||
} else {
|
||||
const { runSetup } = await import('../../core/setup/index.js')
|
||||
await runSetup(cm, { skipRunMode: true, settingsManager, pluginRegistry, instanceRoot: OPENACP_DIR })
|
||||
|
||||
@ -16,63 +16,158 @@ import {
|
||||
generatePluginGuide,
|
||||
} from '../plugin-template/index.js'
|
||||
|
||||
export async function cmdPluginCreate(): Promise<void> {
|
||||
p.intro('Create a new OpenACP plugin')
|
||||
const VALID_LICENSES = ['MIT', 'Apache-2.0', 'ISC', 'UNLICENSED']
|
||||
const NAME_REGEX = /^(@[a-z0-9-]+\/)?[a-z0-9-]+$/
|
||||
|
||||
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)
|
||||
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)' },
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
)
|
||||
{
|
||||
onCancel: () => {
|
||||
p.cancel('Plugin creation cancelled.')
|
||||
process.exit(0)
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const pluginName = result.name.trim()
|
||||
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 dirName = pluginName.replace(/^@[^/]+\//, '') // strip scope for directory name
|
||||
const targetDir = path.resolve(process.cwd(), dirName)
|
||||
const targetDir = cliArgs.dir ? path.resolve(process.cwd(), cliArgs.dir) : path.resolve(process.cwd(), dirName)
|
||||
|
||||
if (fs.existsSync(targetDir)) {
|
||||
p.cancel(`Directory "${dirName}" already exists.`)
|
||||
if (isInteractive) {
|
||||
p.cancel(`Directory "${cliArgs.dir ?? dirName}" already exists.`)
|
||||
} else {
|
||||
console.error(`Error: directory "${cliArgs.dir ?? dirName}" already exists.`)
|
||||
}
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const spinner = p.spinner()
|
||||
spinner.start('Scaffolding plugin...')
|
||||
const spinner = isInteractive ? p.spinner() : null
|
||||
if (spinner) spinner.start('Scaffolding plugin...')
|
||||
|
||||
// Create directory structure
|
||||
fs.mkdirSync(path.join(targetDir, 'src', '__tests__'), { recursive: true })
|
||||
@ -80,9 +175,9 @@ export async function cmdPluginCreate(): Promise<void> {
|
||||
// Collect template params
|
||||
const params: TemplateParams = {
|
||||
pluginName,
|
||||
description: (result.description as string) || '',
|
||||
author: (result.author as string) || '',
|
||||
license: result.license as string,
|
||||
description,
|
||||
author,
|
||||
license,
|
||||
cliVersion: getCurrentVersion(),
|
||||
}
|
||||
|
||||
@ -104,20 +199,26 @@ export async function cmdPluginCreate(): Promise<void> {
|
||||
fs.writeFileSync(path.join(targetDir, file.relativePath), file.content)
|
||||
}
|
||||
|
||||
spinner.stop('Plugin scaffolded!')
|
||||
if (spinner) {
|
||||
spinner.stop('Plugin scaffolded!')
|
||||
}
|
||||
|
||||
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}`)
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user