Compare commits

...

367 Commits

Author SHA1 Message Date
0xmrpeter
cb251ae462 fix(api): accept client-provided turnId in prompt endpoint to prevent SSE echo race condition 2026-04-08 09:22:51 +07:00
0xmrpeter
33503182b4 release: 2026.408.1 2026-04-08 00:58:50 +07:00
0xmrpeter
777735bde8 chore: merge develop into main 2026-04-08 00:57:39 +07:00
Mr.Peter
7ab215f801
Merge pull request #216 from Open-ACP/lucas/fix-agent-available-logic
fix: show Install button for agents with missing external CLI dependencies
2026-04-08 00:57:25 +07:00
0xmrpeter
9e83103574 fix: show Install button for agents with missing external CLI dependencies
Agents like claude-acp and codex-acp wrap external CLIs (claude, codex)
and have an npx/binary distribution in the registry. Previously, missing
external CLIs caused available: false, hiding the Install button entirely
— even though the agent package itself CAN be installed independently.

agent-catalog: for uninstalled agents, available = dist !== null
  Availability now means 'has a distribution to install', not 'all deps
  met'. Missing deps are still surfaced via missingDeps for the UI.

agent-installer: remove hard dep-check block before installation
  Installation proceeds even when external CLIs are absent. The required
  setup steps (e.g. 'npm install -g @anthropic-ai/claude-code') are
  returned in the result so callers can guide the user post-install.
  The uvx runtime check is kept as it is a true hard requirement.
2026-04-08 00:56:11 +07:00
0xmrpeter
b59456115f Merge branch 'develop' 2026-04-07 23:44:03 +07:00
0xmrpeter
35522d386c Merge branch 'lucas/install-node-path-display' into develop 2026-04-07 23:44:03 +07:00
0xmrpeter
1ff14957ad fix: show node binary path in check_node output for easier debugging
Display the resolved path from 'command -v node' alongside the version
so users and logs immediately show which node is active (e.g. nvm vs
system). Also bump installer version to 1.0.3.
2026-04-07 23:43:57 +07:00
0xmrpeter
952ad698c9 Merge branch 'develop' 2026-04-07 23:43:01 +07:00
0xmrpeter
2166d2db6a Merge branch 'lucas/fix-npm-permissions-check' into develop 2026-04-07 23:43:01 +07:00
0xmrpeter
91c2a672d5 fix: prefer nvm over system node and check node_modules write access
Two related bugs caused npm install -g to fail with EACCES on machines
where both system node and nvm-managed node are installed:

1. ensure_default_node_active_shell returned early when system node met
   the minimum version requirement, never sourcing nvm. This caused the
   installer to use system npm (prefix /usr/local, root-owned) instead
   of nvm's npm which has a user-writable prefix.

2. fix_npm_permissions checked -w $prefix/lib which can be writable on
   Intel Macs with Homebrew (/usr/local/lib is user-owned) while
   /usr/local/lib/node_modules remains root-owned from a prior pkg
   install. The check now targets node_modules specifically.
2026-04-07 23:42:53 +07:00
0xmrpeter
7b81fa40f7 merge develop into main 2026-04-07 23:06:46 +07:00
0xmrpeter
69f9d0f2c9 fix: call fix_npm_permissions before both npm and git install paths 2026-04-07 22:54:25 +07:00
0xmrpeter
e8702a15fb fix: call fix_npm_permissions before both npm and git install paths
fix_npm_permissions was only called in the npm install branch, but the
git install path also runs `npm install -g pnpm` as a fallback when
corepack is unavailable. On macOS with Homebrew/system Node, this would
fail with EACCES for the same reason as the main npm install.

Move fix_npm_permissions to run unconditionally before the install
method branch so both paths benefit from the permission fix.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 22:54:19 +07:00
0xmrpeter
191cabe2f9 fix: apply npm permissions fix on macOS, not just Linux 2026-04-07 22:52:51 +07:00
0xmrpeter
bbc5b275bc fix: apply npm permissions fix on macOS, not just Linux
fix_npm_permissions() was guarded with `[[ "$OS" != "linux" ]]`, so it
was a no-op on macOS. Users with Node installed via Homebrew or a system
installer have /usr/local/lib/node_modules owned by root, causing EACCES
on `npm install -g`. Remove the OS guard so the function reconfigures npm
to use ~/.npm-global on any platform where the prefix is not writable.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 22:52:45 +07:00
0xmrpeter
44b658e3db chore: bump version to 2026.407.1
fix(tests): update force_reply assertions to match removed selective flag

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 16:49:42 +07:00
0xmrpeter
5fb0b60355 fix(telegram): remove selective flag from force_reply to auto-open input box
Without selective, Telegram automatically opens the reply compose box
in private chats when bot sends a force_reply message.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 16:45:54 +07:00
0xmrpeter
e521b372ee fix: activate node via nvm/fnm before check_node in non-login shells 2026-04-07 16:43:53 +07:00
0xmrpeter
2084c587e2 fix: activate node via nvm/fnm before check_node in non-login shells
When the install script runs in a non-login shell (e.g. launched from
a GUI app), PATH-based node managers like nvm are not initialized.
Call ensure_default_node_active_shell before check_node so that an
already-installed node is discovered without triggering a redundant
install_node call.
2026-04-07 16:42:53 +07:00
0xmrpeter
83f349c47e fix(tests): update enqueuePrompt assertions and add eventBus mock for API prompt route 2026-04-07 16:12:59 +07:00
0xmrpeter
9f2abea16d Merge branch 'feat/telegram-custom-path-wizard' into develop 2026-04-07 15:56:37 +07:00
0xmrpeter
85fdbf9bf1 fix: resolve defaultAgent options from config.agents when agents.json missing 2026-04-07 15:55:20 +07:00
0xmrpeter
b893fb7062 fix: emit MESSAGE_QUEUED/PROCESSING for API prompts so all SSE clients see user messages
API-sourced prompts (from the App) were bypassing MESSAGE_QUEUED and
MESSAGE_PROCESSING emission, so only the sending App window showed the
user message. Other connected windows only saw the AI response.

- routes/sessions.ts: generate turnId, emit MESSAGE_QUEUED before
  enqueuePrompt, return turnId in response body
- session-bridge.ts: remove 'api' exclusion from MESSAGE_PROCESSING
  so all connected SSE clients receive the streaming stub event
2026-04-07 15:53:18 +07:00
0xmrpeter
24ed74a699 fix: add chatId guard to force-reply interceptor 2026-04-07 15:45:15 +07:00
0xmrpeter
e2759b97ce refactor: remove getAssistantSession param from setupNewSessionCallbacks 2026-04-07 15:42:45 +07:00
0xmrpeter
a9fbdc8340 feat: register force-reply interceptor for custom path wizard 2026-04-07 15:41:13 +07:00
0xmrpeter
8dd6cfd8c3 feat: replace ns:custom AI delegation with force-reply path input 2026-04-07 15:39:33 +07:00
0xmrpeter
06150713ac feat: add force-reply state helpers for telegram custom path wizard
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 15:35:46 +07:00
0xmrpeter
23aa5d0459 docs: add implementation plan for telegram custom path wizard 2026-04-07 15:25:56 +07:00
0xmrpeter
eb07e68aa4 docs: add spec for telegram custom path wizard (no-AI path input) 2026-04-07 15:19:12 +07:00
Mr.Peter
2e01b28330
Merge pull request #215 from lngdao/fix/workspace-basedir
fix: set workspace.baseDir to target directory on instances create/clone
2026-04-07 14:37:35 +07:00
0xmrpeter
0aef31ce74 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-07 14:12:38 +07:00
lngdao
8073235299 fix: set workspace.baseDir to target directory on instances create/clone 2026-04-07 10:41:40 +07:00
0xmrpeter
aa5f25b974 chore: bump version to 2026.406.5 2026-04-06 19:17:36 +07:00
0xmrpeter
3d57f94e8e fix(install): detect nvm without NVM_DIR set in non-login shells
When launched from a GUI app (e.g. OpenACP Desktop), the shell is
non-login so ~/.zshrc is never sourced and NVM_DIR is unset — even
if nvm is properly installed. ensure_default_node_active_shell now
falls back to ~/.nvm/nvm.sh and $XDG_CONFIG_HOME/nvm/nvm.sh when
NVM_DIR is not in the environment.
2026-04-06 19:12:26 +07:00
0xmrpeter
30b868995b chore: bump version to 2026.406.4 2026-04-06 18:39:09 +07:00
0xmrpeter
33af0a98c7 fix(install): detect Homebrew Node in non-login shells
When the installer runs as 'bash install.sh' or 'curl | bash', the shell
is non-login and non-interactive — ~/.zprofile is never sourced, so
Homebrew's /opt/homebrew/bin (Apple Silicon) or /usr/local/bin (Intel)
is missing from PATH. This caused 'command -v node' to return nothing even
when Node 20+ was already installed via Homebrew.

Two changes:
- Init Homebrew shellenv at the very top of the script (before any checks),
  so the full PATH is available for all subsequent commands.
- Add Homebrew path fallback in ensure_default_node_active_shell as a
  belt-and-suspenders guard for cases where early init was skipped.
2026-04-06 18:31:58 +07:00
Mr.Peter
39037f560c
Merge pull request #212 from lngdao/fix/instances-create-flags
fix: instances create — flag forwarding, TTY check, complete config
2026-04-06 17:40:39 +07:00
0xmrpeter
a313b90462 chore: merge develop into main (v2026.406.3) 2026-04-06 17:16:40 +07:00
0xmrpeter
93d85742a1 chore: bump version to 2026.406.3 2026-04-06 17:16:33 +07:00
0xmrpeter
5b132d1b50 feat: add openacp remote to CLI help and assistant guide
Add Remote Access section to `openacp --help` output with all supported
flags. Add `core:remote` assistant section so the AI agent knows how to
generate remote access links, explain roles, tunnel vs local links, and
QR code behavior.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 17:16:23 +07:00
lngdao
15e0e1ef1f fix: instances create generates complete config with SSE channel and defaultAgent 2026-04-06 17:14:39 +07:00
lngdao
e718e2d5f2 fix: set defaultAgent to 'claude' when creating instance without --agent 2026-04-06 17:11:37 +07:00
lngdao
4386cd0b19 fix: skip update prompt when stdin is not a TTY
Prevents interactive update prompt from blocking when CLI is invoked
programmatically (e.g. from Tauri app via invoke_cli).
2026-04-06 17:10:50 +07:00
0xmrpeter
215c64c2cd chore: merge develop into main (v2026.406.2) 2026-04-06 16:47:57 +07:00
0xmrpeter
4495fdbf0b chore: bump version to 2026.406.2 2026-04-06 16:47:47 +07:00
lngdao
24fd15f7f9 fix: forward --dir/--from/--name flags to instances create subcommand
Top-level extractInstanceFlags strips these flags before passing args
to cmdInstances, so cmdInstancesCreate never receives them. Re-inject
parent flags into subArgs when dispatching to create subcommand.
2026-04-06 16:46:57 +07:00
0xmrpeter
9ec2dddb4a fix: improve path/file UX and fix agent relay wiring bug
Workspace path handling:
- Add `allowExternalWorkspaces` config flag (default: true) to allow workspace
  paths outside baseDir; external paths must exist on disk (no auto-create)
- Remove absolute path restriction from WorkspaceNameSchema so agents can pass
  full paths directly to the API
- API route wraps resolveWorkspace() in try/catch and throws BadRequestError
  (HTTP 400 with INVALID_WORKSPACE code) instead of leaking 500 errors
- CLI extractApiError() helper properly extracts .message from structured error
  objects, preventing "[object Object]" display

File attachment handling:
- Add AVIF, HEIC, HEIF to SUPPORTED_IMAGE_MIMES (Claude API supports them)
- Remove filename regex restriction from AttachmentInputSchema (was blocking
  filenames with spaces and unicode)
- Extract attachment logic to attachment-blocks.ts for testability

Security / allowedPaths:
- Propagate config.workspace.security.allowedPaths through AgentManager.spawn()
  and AgentManager.resume() to PathGuard in AgentInstance

Bug fix — agent relay wiring:
- Convert Session.agentInstance to getter/setter so wireAgentRelay() and
  wireCommandsBuffer() are called automatically on any assignment, not just
  via switchAgent(). Fixes 4 pre-existing test failures in session-bridge-switch.
- Fix closure capture bug: wireAgentRelay/wireCommandsBuffer now capture the
  agent instance by value (const instance = this._agentInstance) instead of
  via getter, preventing cleanup from running on the wrong instance when the
  setter assigns a new agent before calling the cleanup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 16:44:26 +07:00
0xmrpeter
8084061c3e feat: propagate sourceAdapterId through middleware to history recorder
Merge sourceAdapterId into routing before enqueue so middleware hooks
(e.g. history recorder) receive it via the agent:beforePrompt payload.
Store sourceAdapterId on user turns in history for downstream use.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 16:03:13 +07:00
0xmrpeter
abe0d8ed29 docs: update CLAUDE.md to reflect the addition of a new middleware hook
- Updated the documentation to indicate the total number of middleware hooks has increased from 18 to 19.
- Adjusted references in the getting-started-plugin guide to ensure consistency with the updated middleware hook count.
- Corrected the middleware hooks section in the plugin template to reflect the accurate total.
2026-04-06 15:50:16 +07:00
0xmrpeter
1327f0f470 refactor: standardize event handling with BusEvent constants
- Replaced string literals in event emissions and middleware executions with BusEvent constants across various modules, enhancing consistency and maintainability.
- Updated event handling in session management, agent switching, and plugin lifecycle to utilize the new BusEvent structure.
- Improved clarity in event-driven architecture by centralizing event definitions.
2026-04-06 15:38:12 +07:00
0xmrpeter
0373225f55 feat: enhance session handling for headless sessions
- Introduced event handling for agent events, status changes, and prompt count updates directly in headless sessions, previously managed by SessionBridge.
- Updated session creation and event emission to exclude assistant sessions from certain notifications.
- Refactored agent event relay wiring to ensure proper event handling across all session types, including headless sessions.
2026-04-06 15:13:32 +07:00
0xmrpeter
c6cb7ff5f7 feat: persistent assistant session (#persistent-assistant-session) 2026-04-06 01:45:13 +07:00
0xmrpeter
15bc3ae4bb fix: address code review issues in persistent assistant session
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:43:31 +07:00
0xmrpeter
3b69880c5d feat: remove /clear command for assistant (no longer needed) 2026-04-06 01:30:14 +07:00
0xmrpeter
67720e2661 feat: expose sessionStore publicly on OpenACPCore for AssistantManager access 2026-04-06 01:29:56 +07:00
0xmrpeter
446071b0e9 feat: replace spawn/respawn with getOrSpawn in AssistantManager
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:27:54 +07:00
0xmrpeter
b395d30919 feat: filter assistant sessions from all session listings
listSessions(), listAllSessions(), and listRecords() now exclude sessions
and records with isAssistant=true so they never appear in user-facing listings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:24:34 +07:00
0xmrpeter
e83a3b08e7 feat: persist isAssistant flag through session creation pipeline
Add isAssistant parameter to SessionCreateParams and createSession method,
then pass it through to the patchRecord call so it gets persisted in the
session record store.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:21:49 +07:00
0xmrpeter
c542f8e837 feat: add findAssistant() to SessionStore and exempt assistant records from TTL cleanup
Added findAssistant() method to SessionStore interface and JsonFileSessionStore implementation
to retrieve the assistant session for a given channel. Updated cleanup() logic to preserve
assistant sessions regardless of TTL expiration.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:20:21 +07:00
0xmrpeter
4c16b59d2f feat: add isAssistant field to SessionRecord type 2026-04-06 01:18:18 +07:00
0xmrpeter
506f04be98 chore: merge develop into main (v2026.406.1)
- chore: bump version to 2026.406.1

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:15:40 +07:00
0xmrpeter
65fbf5469f chore: bump version to 2026.406.1 2026-04-06 01:15:23 +07:00
0xmrpeter
1644f7b888 docs: add persistent assistant session implementation plan
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:11:02 +07:00
0xmrpeter
d9e0a90be7 docs: add persistent assistant session design spec
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 01:04:17 +07:00
0xmrpeter
b1eae11d1e fix(telegram): pass next() in PermissionHandler to unblock menu callbacks
PermissionHandler.setupCallbackHandler() used bot.on('callback_query:data')
without calling next() for non-p: prefixed data, silently consuming all
callback queries and preventing m:, ns:, ar:, c/ handlers from ever firing.

Fix: pass next middleware function and call return next() for unrecognized
callback data so the handler chain continues to the correct handler.

Also add a warn log when a menu item ID is not found in the registry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:37:56 +07:00
0xmrpeter
7247cf28c5 chore: merge develop into main (v2026.405.2)
- fix(telegram): register bot handlers before bot.start() to prevent grammY error
- fix(telegram): guard setupRoutes message handler against uninitialized topic IDs
- test(telegram): add regression tests for adapter startup handler registration order
- chore: bump version to 2026.405.2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:19:55 +07:00
0xmrpeter
3e1dd3d913 fix(telegram): guard setupRoutes message handler against uninitialized topic IDs
Before topics are initialized, this.assistantTopicId is 0. A non-command
message arriving before initTopicDependentFeatures() completes would
generate an invalid redirect URL (t.me/c/.../0).

Add _topicsInitialized guard to the message:text handler in setupRoutes(),
matching the existing guard on the command dispatcher, so messages received
during startup get a clear "still setting up" reply instead of a broken link.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:19:09 +07:00
0xmrpeter
e5eb22072f test(telegram): add regression tests for adapter startup handler registration order
Verifies that all grammY handlers (setupAllCallbacks, setupRoutes) are
registered BEFORE bot.start() is called. The MockBot throws if any handler
registration is attempted after start(), mirroring grammY's real behavior.

This catches the regression where initTopicDependentFeatures() called
setupMenuCallbacks/setupRoutes after bot.start(), causing the bot to silently
fail on startup with grammY's "cannot augment composer after the fact" error.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:14:22 +07:00
0xmrpeter
e0a4ebbc72 chore: bump version to 2026.405.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:11:49 +07:00
0xmrpeter
3e7da2ad7d fix(telegram): register bot handlers before bot.start() to prevent grammY error
grammY throws "cannot augment the composer after the fact" when bot.use()
is called after bot.start(). setupMenuCallbacks and setupRoutes were being
called inside initTopicDependentFeatures(), which runs after bot.start().

Fix: move all handler registration (setupMenuCallbacks, setupRoutes) to
before bot.start() in the start() method. Topic IDs are passed via a
mutable _systemTopicIds ref that is updated in-place by
initTopicDependentFeatures() once topics are ready — callbacks close over
this reference and see correct IDs at invocation time.

Also adds detailed diagnostic logging to validators.ts and adapter.ts
to trace the prerequisite check and topic initialization flow.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 00:07:25 +07:00
Mr.Peter
9dca3462d2
release: v2026.405.1
release: v2026.405.1
2026-04-05 23:19:13 +07:00
0xmrpeter
1a98d0c197 fix(sdk): remove legacyConfig from TestInstallContextOpts
legacyConfig was removed from InstallContext in the config-legacy-removal
refactor but the SDK test helper was not updated, causing build failure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 23:16:09 +07:00
0xmrpeter
e0c6ae55f0 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-05 23:12:23 +07:00
0xmrpeter
897b73354f chore: bump version to 2026.405.1
Also fix api-server test mock missing agentCatalog.load() method.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 23:11:01 +07:00
0xmrpeter
35b2ff9626 fix(merge): use canonical discord-adapter/slack-adapter plugin names
Correct conflict resolution: keep @openacp/discord-adapter and
@openacp/slack-adapter as normalized in faf6286, not the old
@openacp/discord and @openacp/slack names from the refactor branch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 23:06:36 +07:00
0xmrpeter
68fe7b1e96 Merge branch 'refactor/config-legacy-removal' into develop 2026-04-05 23:02:53 +07:00
0xmrpeter
0756c87b0d Merge branch 'feat/api-agent-catalog-reload' into develop 2026-04-05 23:00:54 +07:00
lngdao
d40199799c
feat(api): auto-reload agent catalog on GET /agents (#209)
* feat(api): auto-reload agent catalog on GET /agents, add POST /agents/reload

Re-read agents.json on every GET /agents so newly CLI-installed agents
are visible without restarting the server. Also adds an explicit
POST /agents/reload endpoint for on-demand catalog refresh.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(api): use agents:write scope for reload, extract shared helper

- POST /agents/reload now requires agents:write instead of agents:read
  to better reflect its side-effectful nature
- Extract loadAndListAgents() helper to eliminate code duplication
  between GET /agents and POST /agents/reload
- Add agents:write to KNOWN_SCOPES and operator role in roles.ts
- Add clarifying comment on per-request I/O trade-off

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: 0xmrpeter <0xmrpeter@gmail.com>
2026-04-05 22:56:08 +07:00
0xmrpeter
e96777bc2d fix(api): use agents:write scope for reload, extract shared helper
- POST /agents/reload now requires agents:write instead of agents:read
  to better reflect its side-effectful nature
- Extract loadAndListAgents() helper to eliminate code duplication
  between GET /agents and POST /agents/reload
- Add agents:write to KNOWN_SCOPES and operator role in roles.ts
- Add clarifying comment on per-request I/O trade-off

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:55:53 +07:00
0xmrpeter
ad6b1d9614 feat(api): add permission feedback and broadcast permission:resolved via SSE
Merge feat/api-permission-feedback-prompt

- Add optional `feedback` field to PermissionResponseBodySchema
- When feedback provided with permission deny, abort current turn then queue
  feedback as next prompt (sequential, race-free)
- Broadcast `permission:resolved` event via SSE manager so desktop app and
  other adapters can dismiss permission UI when resolved from another adapter
- Route feedback prompt with correct sourceAdapterId (api/sse)
- Tests covering feedback flow, abort-before-enqueue ordering, and no-op cases
2026-04-05 22:51:44 +07:00
0xmrpeter
4e6425e414 fix(api): await permission feedback abort/enqueue sequentially and add tests
- Await abortPrompt() before enqueuePrompt() to eliminate the race condition
  where enqueued feedback could be cleared by the concurrent queue.clear() call
- Log abortPrompt failures via request.log.warn instead of silently swallowing
- Pass sourceAdapterId routing to enqueuePrompt (api/sse) so agent responses
  are routed correctly
- Add tests for feedback flow in both api-server and sse-adapter route handlers,
  verifying abort-before-enqueue ordering, correct routing, and no-op when no
  feedback is provided

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:51:29 +07:00
0xmrpeter
a60e00d18a Merge fix/file-upload-api into develop
feat(api): add file attachment support to prompt endpoint
2026-04-05 22:43:20 +07:00
0xmrpeter
c16f4170a2 feat(api): add file attachment support to prompt endpoint
Extends POST /sessions/:id/prompt (REST + SSE) to accept an optional
`attachments` array of base64-encoded files. Attachments are decoded
server-side and persisted via FileService, which handles naming,
storage under ~/.openacp/files/{sessionId}/, and PathGuard whitelisting
so agents can read uploaded files without manual path configuration.

Fixes from code review:
- Restore sourceAdapterId/responseAdapterId routing args in enqueuePrompt
  (both REST and SSE routes were dropping them from the original PR)
- Extract shared resolveAttachments() utility to eliminate duplication
  between api-server and sse-adapter routes
- Return 503 with FILE_SERVICE_UNAVAILABLE when file-service plugin is
  not loaded, instead of an unhandled internal error
- Clean up already-written files on partial save failure to avoid orphans
- Validate fileName against safe-char regex at schema level so raw value
  forwarded to agent cannot contain path traversal characters
- Validate mimeType against type/subtype regex to prevent malformed MIME
  values from reaching agent processing
- Raise per-route bodyLimit to 115 MB to make the 10-attachment cap
  reachable (Fastify default 1 MB would reject payloads before schema
  validation otherwise)
- Add .DS_Store to .gitignore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:43:13 +07:00
0xmrpeter
12e7af8da2 feat(telegram): add comprehensive UX improvements for Topics setup
- Introduced a new specification for Telegram Topics UX, addressing user confusion when prerequisites are not met.
- Implemented user-friendly terminology changes, replacing "supergroup" with "group with Topics enabled."
- Enhanced installation flow with warnings and actionable instructions if Topics are disabled or the bot lacks necessary permissions.
- Added runtime checks to ensure prerequisites are met before full initialization, with clear messaging for users during setup.
- Updated documentation to reflect these changes and improve clarity for users.
2026-04-05 22:37:35 +07:00
0xmrpeter
f9fd4d41c2 feat(telegram): improve Topics UX — prerequisite checks, user guidance, terminology fixes 2026-04-05 22:34:50 +07:00
0xmrpeter
914ac48eef fix(telegram): idempotency guard in initTopicDependentFeatures, fix retry message, add network error test
- Add idempotent guard to initTopicDependentFeatures() to prevent multiple initializations
- Update retry message from specific interval to more accurate description
- Add network error test case to validateBotAdmin to verify error handling
2026-04-05 22:33:06 +07:00
0xmrpeter
2075fc4819 docs(telegram): update terminology and document new prerequisite behavior
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:28:14 +07:00
0xmrpeter
88138e29ce fix(telegram): correct prerequisite watcher retry schedule (off-by-one) 2026-04-05 22:25:15 +07:00
0xmrpeter
9f4f688961 feat(telegram): split start() into phases, add prerequisite watcher
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:22:36 +07:00
0xmrpeter
6baf41f0b6 feat(telegram): warn during install when Topics disabled or bot lacks manage-topics perm 2026-04-05 22:18:05 +07:00
0xmrpeter
71c8a3478b feat(telegram): add checkTopicsPrerequisites validator
Add a new exported function checkTopicsPrerequisites(token, chatId) that validates all 3 runtime prerequisites for the Telegram adapter:
1. Topics enabled on the group (is_forum === true)
2. Bot is admin
3. Bot has can_manage_topics permission

Returns { ok: true } if all checks pass, or { ok: false; issues: string[] } with human-readable issue messages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:16:23 +07:00
0xmrpeter
2f9a9c4358 feat(telegram): validateBotAdmin returns canManageTopics
Extended validateBotAdmin to check and return whether the bot has the can_manage_topics permission. The function now returns { ok: true; canManageTopics: boolean } on success for admin/creator bots, allowing callers to determine if topic management is available.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:14:36 +07:00
0xmrpeter
c1482b19c4 fix(telegram): replace supergroup terminology with plain language
Replace internal "supergroup" terminology with user-friendly language in:
- Plugin description: "forum topics" → "Topics support"
- Installation prompt: "Telegram supergroup" → "Telegram group"
- Chat ID labels: "Supergroup chat ID" → "Group chat ID"
- Error message: clearer explanation of chat type requirements
- Comment: reflect plain language terminology

Maintains API type checks (type !== 'supergroup') which are correct.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:12:42 +07:00
0xmrpeter
faf6286e12 fix(onboard): fix channel setup flow and normalize adapter plugin names
- setup-channels: call plugin.install() for first-time setup, plugin.configure()
  for existing channels (was always calling configure())
- setup-channels: add CHANNEL_PLUGIN_NAME map so discord correctly imports
  @openacp/discord-adapter instead of bare 'discord'
- setup-channels: fix delete action to call clear() instead of updatePluginSettings({})
  which was a no-op
- setup-channels: guard SSE channel with early return to prevent failed import
- setup-channels: fix null guard before accessing plugin.name
- setup-channels: fix disable/delete to use correct plugin name per adapter
- Normalize all discord/slack adapter plugin references to canonical names:
  @openacp/discord-adapter and @openacp/slack-adapter
- status.ts: use explicit pluginName→channelId map instead of string replace
- lifecycle-manager: remove stale legacy aliases for old discord/slack names

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 21:32:56 +07:00
lngdao
d082b35f55 feat(api): auto-reload agent catalog on GET /agents, add POST /agents/reload
Re-read agents.json on every GET /agents so newly CLI-installed agents
are visible without restarting the server. Also adds an explicit
POST /agents/reload endpoint for on-demand catalog refresh.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 18:39:52 +07:00
0xmrpeter
8a0b6166a1 fix(session-factory): fallback to spawn with context injection when agent session expires after restart 2026-04-05 18:04:36 +07:00
0xmrpeter
4c79487d7c fix(agent-switch): flush history and bypass cache before context injection; resume agents with prior prompts 2026-04-05 17:43:11 +07:00
0xmrpeter
2b59db122e feat(context-plugin): wire recorder flusher into ContextManager 2026-04-05 17:41:33 +07:00
0xmrpeter
976e4ded91 feat(context-manager): add flushSession() and noCache support in buildContext 2026-04-05 17:41:17 +07:00
0xmrpeter
e0f481bc9a feat(history-recorder): add flush() method for pre-switch drain 2026-04-05 17:40:53 +07:00
0xmrpeter
3d584f7ed4 feat(context): add noCache option to ContextOptions 2026-04-05 17:40:12 +07:00
0xmrpeter
29eb319400 fix(config): restore delete-display-verbosity migration lost in merge conflict
The migration was accidentally dropped when resolving conflicts with PR #208
(config legacy removal). Re-add it to ensure the legacy displayVerbosity key
is cleaned up from existing user configs on upgrade.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 17:07:09 +07:00
0xmrpeter
0aab4e63e8 chore: resolve merge conflicts with develop (config legacy removal)
All conflicts resolved in favor of the merged refactor branch (PR #208):
- config-migrations.ts: keep only add-instance-name migration
- config.ts (assistant section): remove speech legacy fallback
- config-section.test.ts: remove legacy speech tests
- speech-plugin-setup.test.ts: remove legacyConfig test cases
- design spec: keep merged version

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 17:01:47 +07:00
Mr.Peter
179f36442d
refactor: remove legacy config sections and add plugin field declaration API (#208)
* fix(speech): STT not working when plugin settings missing groqApiKey

Fixes two bugs reported in #198 where STT feature does not work despite
being marked as configured.

Bug 1: speech plugin setup() now falls back to reading the API key from
legacy config.json (ctx.config) when groqApiKey is absent from plugin
settings. This handles users who upgraded OpenACP without reinstalling
the speech plugin, so the install() migration was never triggered. A
warn log is emitted to guide permanent migration via
`openacp plugin configure @openacp/speech`.

Bug 2: createConfigSection now uses SpeechService.isSTTAvailable() from
the ServiceRegistry to determine STT status, rather than reading from the
legacy config.json field. This ensures the assistant status snapshot
reflects actual runtime state instead of showing a false positive.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add config legacy removal design spec

Spec for two-phase removal of legacy config sections from ConfigSchema,
env var deduplication, and plugin self-declaring editable fields.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: remove legacy sections from ConfigSchema

Remove channels, agents, security, api, tunnel, usage, speech sections.
These now live exclusively in plugin settings files.
BaseChannelSchema, AgentSchema, TunnelSchema, UsageSchema, SpeechSchema
and their exported types are deleted.
DEFAULT_CONFIG simplified to core-only fields.

* fix: update all files referencing removed ConfigSchema fields

Replace config.agents/security/api/tunnel/speech/channels references
with agents.json reads or plugin settings reads. Fixes TypeScript errors
from ConfigSchema cleanup in previous commit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: remove legacy config migrations

Keep only add-instance-name migration (needed for new installs).
Delete plugin-config-migration.ts (unused scaffolding, never integrated).

* refactor: remove plugin-mapped fields from config-registry

Remove: channels.telegram.outputMode, channels.discord.outputMode,
tunnel.enabled, security.maxConcurrentSessions, security.sessionTimeoutMinutes,
speech.stt.provider, speech.stt.apiKey.
Remove plugin? field from ConfigFieldDef — plugins self-declare via
registerEditableFields() in Phase 2.
Remove getFieldValueAsync, slim setFieldValueAsync to 3 params.

* refactor: config-editor reads/writes plugin fields via settings only

Drop config.json fallback in editTelegram, editSecurity, editApi, editTunnel.
These functions now exclusively use SettingsManager for plugin-owned fields.

* test: remove legacy config test cases

Delete: config-env-overrides.test.ts (channel token env overrides),
  config-registry-plugin.test.ts (getFieldValueAsync, plugin-mapped setFieldValueAsync)
Trim: config-migrations.test.ts (keep only add-instance-name),
  config-registry.test.ts (remove tunnel/channels assertions),
  install-context.test.ts and plugin-setup-integration.test.ts
  (remove legacyConfig test cases).

Also trim pre-existing failures from Phase 1 schema changes:
  config-schema.test.ts (remove channels/api/security refs),
  config-workspace.test.ts (remove channels/security/tunnel env override tests),
  api-server.test.ts (update mock config, 429 test, PATCH config test),
  routes-sessions.test.ts (fix 429 via lifecycleManager.settingsManager mock),
  setup-integration.test.ts (remove channels/agents/security assertions),
  helpers.test.ts and setup-channels.test.ts (remove legacy config.channels tests),
  config-section.test.ts (remove legacy speech provider tests),
  multi-instance-plumbing.test.ts (remove migrate-agents-to-store test).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add FieldDef type and registerEditableFields to PluginContext

Plugins can now declare their editable settings fields in setup():
  ctx.registerEditableFields([
    { key: 'botToken', displayName: 'Bot Token', type: 'string', scope: 'sensitive' },
  ])
Fields are stored in PluginFieldRegistry (service: 'field-registry').
Requires 'commands:register' permission.

* refactor: remove legacyConfig from InstallContext

Plugin install() hooks no longer receive legacy config.json data.
Interactive setup is the only install path going forward.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: remove legacyConfig from telegram, security, speech plugins

Each plugin's install() now has only the interactive setup path.
Added registerEditableFields() calls in each plugin's setup() hook.
Remove speech legacy config fallback (config.speech no longer exists).

Also export FieldDef from @openacp/cli public API and add
registerEditableFields() no-op stub to createTestContext() in plugin-sdk.
Remove speech-plugin-setup test case for legacy config fallback path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: remove legacyConfig from tunnel, api-server, file-service plugins

Completes legacyConfig removal from all plugins.
Added registerEditableFields() to each plugin's setup() hook.
Added commands:register permission to api-server and file-service plugins
to satisfy registerEditableFields() permission requirement.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: export FieldDef from plugin-sdk

Plugin authors can import FieldDef from @openacp/plugin-sdk to type
their registerEditableFields() calls.

* fix: add commands:register to telegram, clean up dead legacyConfig in main.ts, update plugin template

- Add missing commands:register permission to telegram plugin (required by registerEditableFields)
- Remove dead legacyConfig variable from autoRegisterBuiltinPlugins in main.ts
- Remove legacyConfig documentation from plugin template (field removed from InstallContext)

* test: add missing coverage for config legacy removal

- config-registry: exact 5-field count, removed plugin fields absent,
  setFieldValueAsync 3-arg API with return values and validation
- config-schema: removed fields (channels, security, tunnel) are stripped,
  outputMode and agentSwitch core fields work correctly
- plugin-context: registerEditableFields permission guard and registry wiring
- install-context: assert legacyConfig absent from context

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add Discord and Slack env var override tests for applyEnvToPluginSettings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 16:58:27 +07:00
0xmrpeter
48250b7263 fix: comprehensive security hardening and reliability improvements
Address 23 issues found during full codebase review:

Security (Critical):
- Replace hand-rolled HTML sanitizer with sanitize-html library (allowlist approach)
- Fix shell injection in plugin installer (exec → execFile with array args)
- Add zip pre-extraction validation to prevent path traversal
- Block prototype pollution in config deepMerge
- Add redirect limit (max 10) and fix command injection in install-binary
- Fix token store silently swallowing save errors (revocations could be lost)

Process & Data Integrity:
- Fix cancelSession not destroying agent subprocess (process leak)
- Fix failed session registered but never cleaned up
- Fix session-store cleanup crash on null lastActiveAt
- Make config save() atomic (write-to-temp-then-rename)

Reliability:
- Isolate EventBus listener errors (one bad listener no longer breaks all)
- Fix multi-bridge relay duplicating events N times
- Fix PromptQueue abort race breaking serial execution guarantee
- Fix CommandRegistry.unregister deleting wrong plugin's command
- Add MessageTransformer session cache cleanup on disconnect
- Add TypedEmitter max buffer size (10000) to prevent unbounded growth
- Fix Draft flush() race condition losing buffer content
- Fix nodeToWebWritable event listener leak on backpressure
- Auto-cleanup exited terminals after 30s grace period
- Fix TerminalManager waitForExit TOCTOU race
- Clean up PluginContext menu items and assistant sections on plugin unload
- Only trust X-Forwarded-For for rate limiting when behind proxy
- Fix workspace cache eviction deleting all entries instead of stale ones
- Delete legacy displayVerbosity key during config migration

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:54:47 +07:00
0xmrpeter
4d9e066995 test: add Discord and Slack env var override tests for applyEnvToPluginSettings
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 14:58:24 +07:00
0xmrpeter
5668f6f6ca test: add missing coverage for config legacy removal
- config-registry: exact 5-field count, removed plugin fields absent,
  setFieldValueAsync 3-arg API with return values and validation
- config-schema: removed fields (channels, security, tunnel) are stripped,
  outputMode and agentSwitch core fields work correctly
- plugin-context: registerEditableFields permission guard and registry wiring
- install-context: assert legacyConfig absent from context

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 14:17:51 +07:00
0xmrpeter
8b24b8921e fix: add commands:register to telegram, clean up dead legacyConfig in main.ts, update plugin template
- Add missing commands:register permission to telegram plugin (required by registerEditableFields)
- Remove dead legacyConfig variable from autoRegisterBuiltinPlugins in main.ts
- Remove legacyConfig documentation from plugin template (field removed from InstallContext)
2026-04-05 14:10:21 +07:00
0xmrpeter
416b78fc6e feat: export FieldDef from plugin-sdk
Plugin authors can import FieldDef from @openacp/plugin-sdk to type
their registerEditableFields() calls.
2026-04-05 14:04:56 +07:00
0xmrpeter
3ada6cbe13 refactor: remove legacyConfig from tunnel, api-server, file-service plugins
Completes legacyConfig removal from all plugins.
Added registerEditableFields() to each plugin's setup() hook.
Added commands:register permission to api-server and file-service plugins
to satisfy registerEditableFields() permission requirement.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 14:03:56 +07:00
0xmrpeter
10836a33c6 refactor: remove legacyConfig from telegram, security, speech plugins
Each plugin's install() now has only the interactive setup path.
Added registerEditableFields() calls in each plugin's setup() hook.
Remove speech legacy config fallback (config.speech no longer exists).

Also export FieldDef from @openacp/cli public API and add
registerEditableFields() no-op stub to createTestContext() in plugin-sdk.
Remove speech-plugin-setup test case for legacy config fallback path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 14:01:19 +07:00
0xmrpeter
63a30d3ef4 refactor: remove legacyConfig from InstallContext
Plugin install() hooks no longer receive legacy config.json data.
Interactive setup is the only install path going forward.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 13:56:16 +07:00
0xmrpeter
f3230dbc92 feat: add FieldDef type and registerEditableFields to PluginContext
Plugins can now declare their editable settings fields in setup():
  ctx.registerEditableFields([
    { key: 'botToken', displayName: 'Bot Token', type: 'string', scope: 'sensitive' },
  ])
Fields are stored in PluginFieldRegistry (service: 'field-registry').
Requires 'commands:register' permission.
2026-04-05 13:55:18 +07:00
0xmrpeter
0f93c9e2ed test: remove legacy config test cases
Delete: config-env-overrides.test.ts (channel token env overrides),
  config-registry-plugin.test.ts (getFieldValueAsync, plugin-mapped setFieldValueAsync)
Trim: config-migrations.test.ts (keep only add-instance-name),
  config-registry.test.ts (remove tunnel/channels assertions),
  install-context.test.ts and plugin-setup-integration.test.ts
  (remove legacyConfig test cases).

Also trim pre-existing failures from Phase 1 schema changes:
  config-schema.test.ts (remove channels/api/security refs),
  config-workspace.test.ts (remove channels/security/tunnel env override tests),
  api-server.test.ts (update mock config, 429 test, PATCH config test),
  routes-sessions.test.ts (fix 429 via lifecycleManager.settingsManager mock),
  setup-integration.test.ts (remove channels/agents/security assertions),
  helpers.test.ts and setup-channels.test.ts (remove legacy config.channels tests),
  config-section.test.ts (remove legacy speech provider tests),
  multi-instance-plumbing.test.ts (remove migrate-agents-to-store test).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 13:52:51 +07:00
0xmrpeter
1b58423755 refactor: config-editor reads/writes plugin fields via settings only
Drop config.json fallback in editTelegram, editSecurity, editApi, editTunnel.
These functions now exclusively use SettingsManager for plugin-owned fields.
2026-04-05 13:43:37 +07:00
0xmrpeter
a88f69e470 refactor: remove plugin-mapped fields from config-registry
Remove: channels.telegram.outputMode, channels.discord.outputMode,
tunnel.enabled, security.maxConcurrentSessions, security.sessionTimeoutMinutes,
speech.stt.provider, speech.stt.apiKey.
Remove plugin? field from ConfigFieldDef — plugins self-declare via
registerEditableFields() in Phase 2.
Remove getFieldValueAsync, slim setFieldValueAsync to 3 params.
2026-04-05 13:40:52 +07:00
0xmrpeter
892b87a039 refactor: remove legacy config migrations
Keep only add-instance-name migration (needed for new installs).
Delete plugin-config-migration.ts (unused scaffolding, never integrated).
2026-04-05 13:38:55 +07:00
0xmrpeter
a276154742 fix: update all files referencing removed ConfigSchema fields
Replace config.agents/security/api/tunnel/speech/channels references
with agents.json reads or plugin settings reads. Fixes TypeScript errors
from ConfigSchema cleanup in previous commit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 13:37:27 +07:00
0xmrpeter
3281976826 refactor: remove legacy sections from ConfigSchema
Remove channels, agents, security, api, tunnel, usage, speech sections.
These now live exclusively in plugin settings files.
BaseChannelSchema, AgentSchema, TunnelSchema, UsageSchema, SpeechSchema
and their exported types are deleted.
DEFAULT_CONFIG simplified to core-only fields.
2026-04-05 13:28:22 +07:00
0xmrpeter
007012fef1 docs: add config legacy removal implementation plan
Two-phase plan covering ConfigSchema cleanup, env var deduplication,
config-editor migration, PluginFieldRegistry, and legacyConfig removal
from all 6 affected plugins.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 13:11:29 +07:00
0xmrpeter
d6a1321784 docs: fix config legacy removal spec after review
- Correct plugin list: remove discord/slack/usage (don't exist), add file-service
- Add config-editor.ts to Phase 1 impact (was missing, heavy legacy references)
- Note BaseChannelSchema removal alongside channels section
- Clarify usage section: remove from schema, no plugin migration needed
- Fix InstallContext type file reference (types.ts not plugin-context-types.ts)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 13:03:37 +07:00
0xmrpeter
4371823763 docs: add config legacy removal design spec
Spec for two-phase removal of legacy config sections from ConfigSchema,
env var deduplication, and plugin self-declaring editable fields.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 12:59:04 +07:00
0xmrpeter
3f501a373c fix(speech): STT not working when plugin settings missing groqApiKey
Fixes two bugs reported in #198 where STT feature does not work despite
being marked as configured.

Bug 1: speech plugin setup() now falls back to reading the API key from
legacy config.json (ctx.config) when groqApiKey is absent from plugin
settings. This handles users who upgraded OpenACP without reinstalling
the speech plugin, so the install() migration was never triggered. A
warn log is emitted to guide permanent migration via
`openacp plugin configure @openacp/speech`.

Bug 2: createConfigSection now uses SpeechService.isSTTAvailable() from
the ServiceRegistry to determine STT status, rather than reading from the
legacy config.json field. This ensures the assistant status snapshot
reflects actual runtime state instead of showing a false positive.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 12:38:21 +07:00
0xmrpeter
f45dc494f6 fix(api-server): POST /sessions without channel creates headless session
Previously, omitting the `channel` param when creating a session via
POST /sessions would silently fall back to the first registered adapter
(e.g. Telegram), creating an unintended platform thread. This was
non-deterministic in multi-adapter setups and wrong for API-only callers.

Now, omitting `channel` explicitly produces a headless session
(channelId: 'api', createThread: false). API callers interact via SSE +
POST /sessions/:id/prompt. Use POST /sessions/:id/attach to wire an
adapter thread after creation.

Fixes #76

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 11:42:07 +07:00
0xmrpeter
027e0f99a6 fix(plugin-create): rename --dir to --output/-o to avoid instance flag conflict
The top-level extractInstanceFlags() consumes --dir as an instance
directory flag, preventing it from reaching plugin create. Renamed to
--output/-o which doesn't conflict. Also fixed display path formatting.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:23:38 +07:00
0xmrpeter
7b206f8124 chore: merge main into develop
Resolve conflicts in display-spec-builder.ts and formatting.ts:
- Keep JSDoc comments from develop
- Take normalizePathLike + comma-separated path handling from main's formatting.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 10:18:44 +07:00
0xmrpeter
71682f72d3 feat(plugin-create): add non-interactive CLI mode and improve display specs
- Add non-interactive mode to `openacp plugin create` with --name, --description,
  --author, --license, --dir flags; positional name arg also supported
- Fix --help routing for plugin subcommands (was eating help for create/search)
- display-spec-builder: support camelCase field names (OpenCode compat), add
  apply_patch and TodoWrite title handlers, expose workingDirectory on ToolDisplaySpec
- telegram formatting: relativize file paths against workingDirectory when available,
  fall back to basename; use basename for link labels

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 10:15:19 +07:00
Mr.Peter
bb7de274d2
fix(integrate): standardize path construction in buildHandoffItem.isInstalled (#207)
Use join(expandPath(base), file) consistently for plugin integration paths,
matching the pattern already used in installPluginIntegration and
uninstallPluginIntegration.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 10:10:25 +07:00
hightman
6f77aed353
feat(integrate): add OpenCode session handoff integration (#205)
* feat(integrate): add opencode handoff plugin strategy

Add a plugin-based integration path so OpenCode can hand off sessions bidirectionally while preserving the existing hooks flow for other agents. This enables /openacp:handoff in OpenCode and avoids jq requirements for that integration.

Co-authored-by: Codex <noreply@openai.com>

* fix(integrate): address PR review for opencode strategy

Make integration strategy discriminated and exhaustive, harden OpenCode injected text part shape, and improve plugin install/uninstall idempotency and messaging. Add regression tests for reinstall and empty uninstall paths.
Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: 0xmrpeter <0xmrpeter@gmail.com>

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: 0xmrpeter <0xmrpeter@gmail.com>
2026-04-05 10:07:19 +07:00
lngdao
4518267bfb feat(api): add permission feedback and broadcast permission:resolved via SSE
- Add optional `feedback` field to PermissionResponseBodySchema
- When feedback provided with permission deny, queue it as next prompt
  so the agent processes user's alternative instructions after the
  denial turn completes
- Broadcast `permission:resolved` event via SSE manager so desktop app
  and other adapters can dismiss permission UI when resolved elsewhere
2026-04-04 23:14:50 +07:00
Mr.Peter
c873230761
fix(telegram): align OpenCode tool display with adapter boundaries (#203)
fix(telegram): improve tool card context for file operations
2026-04-04 23:12:16 +07:00
codex
565a70b69c fix(telegram): align OpenCode tool display with adapter boundaries
Improve OpenCode compatibility by handling camelCase filePath across file tools and adding stable apply_patch/todowrite title extraction in the core display builder. Move path relativization to Telegram formatting via workingDirectory so Telegram shows clearer relative paths while other adapters keep raw paths.
2026-04-04 13:40:45 +08:00
Mr.Peter
89c6ab02b1
feat(install): enhance npm resolution in Windows install script
feat(install): enhance npm resolution in Windows install script
2026-04-04 10:46:53 +07:00
0xmrpeter
4a2e574e2c Merge branch 'main' of github.com:Open-ACP/OpenACP 2026-04-04 09:39:46 +07:00
0xmrpeter
8273dcc2ba chore: merge develop into main 2026-04-04 09:39:17 +07:00
qm1719
e1f90feacd feat(install): enhance npm resolution in Windows install script
Problem:
1. line 238 contains mojibake (UTF-8 em dash mis-decoded) and a curly closing quote (U+201D) instead of ASCII ", so the string never terminates and { is parsed as code. Fixing the string to use ASCII quotes and a normal hyphen.
2. On Windows, npm is implemented as npm.ps1. For many invocations it does not use $args; it takes the original command text, parses it again with PowerShell, and runs something like Invoke-Expression to call node with rebuilt arguments. A scoped package like @openacp/cli@latest is parsed incorrectly (because of @), so the args handed to npm are wrong and I got "Unknown command: "pm"".
Changes proposed:
- Introduced a new function, Resolve-NpmExecutable, to determine the correct npm executable for Windows environments.
- Updated Install-OpenACPNpm and Main functions to utilize the resolved npm executable, ensuring compatibility and reliability during installation.
- Improved logging for dry-run scenarios and retry attempts during npm installation.
- Manually tested and succeed
2026-04-04 09:35:07 +07:00
0xmrpeter
4561a602c0 fix: address code review issues in resilient history saving
- Add "error" and "interrupted" to StopReason type (removes unsafe cast)
- Clear activeTurnContext in finally block so routing state is never stale after errors
- Fix onSessionDestroy to delegate cleanup to finalize() instead of duplicating logic
- Move onSessionDestroy debounce test into fake timer describe block (prevent timer leak)
- Fix misleading "or cancel" in turn:end comment

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 02:04:40 +07:00
0xmrpeter
33d4f70342 feat: wire onSessionDestroy in context plugin for mid-turn flush on session cleanup
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 02:00:44 +07:00
0xmrpeter
50255e9743 feat: add debounced auto-save and onSessionDestroy flush to HistoryRecorder
- Schedule debounced write (2s) after each event to minimize data loss on crash
- Add onSessionDestroy() to flush in-progress turns as "interrupted" on cleanup
- Cancel debounce timer in onTurnEnd and finalize to prevent double-writes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 02:00:21 +07:00
0xmrpeter
25616f7d68 fix: fire turn:end middleware in finally so errors and cancels always save history
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:59:02 +07:00
0xmrpeter
91ad6c7c81 chore: bump version to 2026.404.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:36:24 +07:00
Mr.Peter
75ae2e36fd
Merge pull request #202 from Open-ACP/feat/file-attachment-api-fixed
feat: cross-adapter SSE visibility + lazy resume by session ID
2026-04-04 01:35:08 +07:00
0xmrpeter
1d8b2adc8b fix: emit message:queued immediately before awaiting prompt queue
queue.enqueue() blocks until the item is fully processed, so emitting
message:queued after awaiting it caused the event to fire only after AI
finishes — showing the Telegram message after the AI response.

Fix: generate turnId upfront, emit message:queued synchronously before
the await, then pass the pre-generated turnId into enqueuePrompt so that
message:processing later shares the same turnId.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:32:48 +07:00
0xmrpeter
cc5625d5ee fix: fallback to channelId as sourceAdapterId for message:queued event
Adapters that don't explicitly set routing.sourceAdapterId (e.g. Telegram)
were silently dropping the message:queued EventBus emission, preventing SSE
clients from seeing cross-adapter input messages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:17:03 +07:00
0xmrpeter
9ea46457de feat: emit message:queued and message:processing events for cross-adapter input visibility
SSE /events stream now receives input messages from external adapters (Telegram, Discord)
with full metadata and queue lifecycle state so app can display conversation history
and accurate typing indicators.

- Add message:queued EventBus event emitted in core.handleMessage() after enqueue
  (skipped for sse/api sources — app already knows its own messages)
- Add message:processing EventBus event emitted via session-bridge turn_started listener
- Generate turnId at enqueue time so both events share the same ID for client pairing
- Pass pre-generated turnId through queue → createTurnContext() to avoid ID mismatch
- SSEManager subscribes to both new events and filters them by sessionId

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:08:26 +07:00
0xmrpeter
0b17f88285 chore: bump version to 2026.404.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 01:03:38 +07:00
0xmrpeter
5b7fee0e92 fix: improve tunnel fallback handling and logging
- Update tunnel service to log detailed error messages when the OpenACP tunnel fails and falls back to Cloudflare.
- Enhance the main server logic to only warn about tunnel failures if the fallback is not in use, providing clearer feedback on tunnel status.
- Ensure fallback URLs are logged for better visibility during tunnel transitions.
2026-04-04 01:03:12 +07:00
0xmrpeter
d33f975ce7 fix: restore EventBus agent:event emission for non-forwarded events and add lazy resume by session ID
- Emit agent:event on EventBus even when shouldForward()=false so /events SSE
  stream receives all agent events regardless of which adapter owns the bridge
- Add SessionFactory.getOrResumeById() to resume historical sessions directly
  by session ID without needing channelId+threadId lookup
- Expose OpenACPCore.getOrResumeSessionById() and use it in POST prompt route
  so the app can send prompts to sessions that are in storage but not yet live

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 00:51:33 +07:00
0xmrpeter
69d73c981b docs: add file attachment API spec and implementation plan 2026-04-04 00:09:42 +07:00
Mr.Peter
25e5eb85cd
Merge pull request #200 from Open-ACP/feature/multi-adapter-session-routing
feat: multi-adapter session routing
2026-04-03 23:19:12 +07:00
0xmrpeter
e3f017e05d docs: add session list history spec and plan 2026-04-03 23:00:16 +07:00
0xmrpeter
4075d87f6a fix: multi-adapter permission handling, lazy resume, platforms persistence, type safety
- session-bridge: only register onPermissionRequest on primary bridge (guard via __bridgeId);
  secondary bridges forward permission UI via session event listener; disconnect only clears
  handler if this bridge owns it; emit permission_request after setPending for correct ordering
- session-factory: lazyResume predicate checks both topicId and threadId for non-Telegram adapters
- core: createSession and adoptSession now write platforms field alongside legacy platform field
  so lazy resume can find sessions on non-Telegram adapters
- sessions route: remove as-any casts for attachAdapter/detachAdapter (OpenACPCore has these methods)
- sessions schema: add sourceAdapterId and responseAdapterId to PromptBodySchema; prompt handler
  reads routing fields from validated body instead of raw request.body as any

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:54:17 +07:00
0xmrpeter
4564d392e2 test: nest listAllSessions tests inside SessionManager describe block
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:54:09 +07:00
0xmrpeter
38ca66f36b test: assert lastActiveAt in historical session route test 2026-04-03 22:52:00 +07:00
0xmrpeter
608a24ceff feat: GET /sessions returns full session history via listAllSessions
Replace listSessions() with listAllSessions() in the GET /sessions route
handler so it returns both live and historical sessions with the full
SessionSummary shape (isLive, lastActiveAt, channelId). Update all
affected test mocks to use the new API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:49:22 +07:00
0xmrpeter
7b91ca2203 fix: export SessionSummary type from core public API 2026-04-03 22:46:16 +07:00
0xmrpeter
aec7cbd0f8 feat: add SessionSummary + listAllSessions() to SessionManager
Adds the SessionSummary interface and listAllSessions() method that merges
live in-memory session data with historical store records, supporting
channelId filtering and graceful fallback when no store is configured.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:43:45 +07:00
0xmrpeter
eae34bbdb7 test: update enqueuePrompt assertions for sourceAdapterId routing 2026-04-03 22:26:54 +07:00
0xmrpeter
78d844ee64 feat: export TurnContext types from core 2026-04-03 22:25:50 +07:00
0xmrpeter
ceecbced9a feat: broadcast permission:resolved event for multi-adapter UI cleanup 2026-04-03 22:25:33 +07:00
0xmrpeter
e3366024f2 feat: SSE adapter passes sourceAdapterId on prompt 2026-04-03 22:24:54 +07:00
0xmrpeter
a5d74b0e34 feat: add attach/detach API endpoints with sourceAdapterId routing 2026-04-03 22:24:43 +07:00
0xmrpeter
23303c80b7 feat: restore multi-adapter state on lazy resume 2026-04-03 22:24:21 +07:00
0xmrpeter
9834029f7e feat: agent switch disconnects and reconnects all attached adapter bridges
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:22:41 +07:00
0xmrpeter
62f2462d93 feat: multi-bridge Core pipeline with attachAdapter/detachAdapter
- Change bridges Map key from sessionId to composite "adapterId:sessionId"
- Add bridgeKey() and getSessionBridgeKeys() helpers
- Update createBridge() to accept optional adapterId param and use composite key
- Update createSession/connectSessionBridge to pass explicit channelId as adapterId
- Update handleMessage to forward message.routing to enqueuePrompt
- Add attachAdapter() to create a secondary bridge on a new adapter+thread
- Add detachAdapter() to cleanly disconnect a non-primary adapter
- Add buildPlatformsFromSession() helper for persisting multi-adapter state
- Fix AgentSwitchHandler to look up bridges using composite key

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:20:26 +07:00
0xmrpeter
58d08a13b6 feat: update session thread lookup for multi-adapter threadIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:17:33 +07:00
0xmrpeter
de4cb590ab feat: add platforms and attachedAdapters to SessionRecord with auto-migration
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:16:57 +07:00
0xmrpeter
97cc32a9d6 feat: turn-aware multi-bridge routing in SessionBridge
Add adapterId field and shouldForward() method to SessionBridge so that
turn events are routed only to the matching adapter while system events
broadcast to all attached bridges; silent turns (responseAdapterId=null)
suppress all turn events. Backward-compatible: null activeTurnContext
forwards everything as before.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:15:34 +07:00
0xmrpeter
c42b2cf7f0 feat: add multi-adapter fields and turn-aware enqueue to Session
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:12:56 +07:00
0xmrpeter
17d14e9b01 feat: add TurnRouting to PromptQueue and IncomingMessage
- Re-export TurnRouting from types.ts (public API)
- Add routing?: TurnRouting field to IncomingMessage interface
- Update PromptQueue to carry routing metadata with each queued item
- Processor now receives (text, attachments, routing) parameters
- Update tests to account for new routing parameter

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:09:18 +07:00
0xmrpeter
94b5648084 test: add getEffectiveTarget tests to turn-context 2026-04-03 22:07:16 +07:00
0xmrpeter
be7dccb6a1 feat: add TurnContext type and event classification
Create TurnContext module for multi-adapter session routing, decoupling sessions
from adapters. Provides event classification to route system events to all adapters
and turn events only to the response adapter.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:04:55 +07:00
0xmrpeter
8161fe35c7 fix: handle graceful shutdown signals in agent instance 2026-04-03 21:58:44 +07:00
0xmrpeter
7b6c96828d Add multi-adapter session routing implementation plan
14 tasks covering: TurnContext, PromptQueue routing, Session multi-adapter
fields, SessionBridge turn-aware routing, SessionRecord migration,
SessionManager lookup, Core pipeline with attach/detach, AgentSwitch
multi-bridge, SessionFactory resume, API endpoints, SSE routing,
permission resolved broadcast.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:57:13 +07:00
0xmrpeter
1f0297cce5 Add multi-adapter session routing design spec
Sessions become global with per-session multi-bridge architecture.
Any adapter can attach/detach from sessions via explicit action.
Turn-based response routing with sealed TurnContext per event.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:51:04 +07:00
0xmrpeter
ffae9763ab fix: clean up listener leak in wireCommandsBuffer, add destroyAll comment, improve catch comment 2026-04-03 20:41:55 +07:00
0xmrpeter
cff8de0213 fix: only use cached acpState as fallback when agent provides no config on resume
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 20:33:29 +07:00
0xmrpeter
d2509efd8c fix: shutdownAll snapshots full session state including acpState
Persist acpState, clientOverrides, currentPromptCount, and agentSwitchHistory
during graceful shutdown so state changes within the debounce window are not
lost on restart.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 20:33:12 +07:00
0xmrpeter
ef9c03fbee fix: /switch notifies user when queued prompts are dropped 2026-04-03 20:32:30 +07:00
0xmrpeter
ea4a1e66c6 fix: all config commands use session.setConfigOption() for consistent middleware flow
Refactor category commands (/mode, /model, /thought) and bypass_permissions to
call session.setConfigOption() instead of agentInstance.setConfigOption() directly,
ensuring middleware hooks and configOptions updates are handled consistently.
Update tests to mock session.setConfigOption() instead of agentInstance.setConfigOption().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 20:31:12 +07:00
0xmrpeter
96b06a8206 fix: remove bridge from map before disconnect, add reconnect error handling 2026-04-03 20:28:17 +07:00
0xmrpeter
2860b42f49 fix: abort running prompt before agent switch in API endpoint 2026-04-03 20:28:01 +07:00
0xmrpeter
9677f623ad fix: update mock updateConfigOptions to return Promise (match async signature) 2026-04-03 20:27:01 +07:00
0xmrpeter
3fab446bbe fix: await updateConfigOptions before persisting ACP state in bridge
The config_option_update handler in SessionBridge was calling
persistAcpState() synchronously before updateConfigOptions() (which runs
async middleware) could complete, potentially persisting stale state.
Chain persistAcpState() in the resolved .then() callback instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 20:26:03 +07:00
0xmrpeter
ce9ed32a73 fix: re-register commands_update buffer listener after agent switch
The commands_update buffer listener was only registered in the constructor,
so after switchAgent() replaced agentInstance, events from the new agent
were silently dropped. Extracted wireCommandsBuffer() and call it in both
the constructor and at the end of switchAgent().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 20:22:52 +07:00
0xmrpeter
89c67176bc chore: bump version to 2026.403.8
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 19:06:30 +07:00
0xmrpeter
0dbaa518cf fix: enhance session configuration handling and legacy support
- Updated the `setConfigOption` method in the `Session` class to optimistically update the current value for select options when legacy agents return empty configOptions.
- Introduced a new method `applySpawnResponse` in the `Session` class to handle both native and legacy configOptions formats.
- Improved error logging in the `setConfigOption` method for better debugging.
- Added tests to ensure correct behavior for legacy fallback scenarios in the `Session` class and `AgentInstance` methods.

This change improves compatibility with legacy agents and enhances the overall robustness of session configuration management.
2026-04-03 19:03:04 +07:00
0xmrpeter
5818dbfdae chore: bump version to 2026.403.7
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 16:35:08 +07:00
0xmrpeter
8a8a80f3e9 fix: persist topicId to disk atomically on session creation
The lazy-resume flow failed after server restart because topicId was
written in a separate debounced patchRecord call (2-second window).
If the server restarted before that debounce fired, the on-disk record
had platform:{} with no topicId, so findByPlatform returned null and
the session could not be resumed.

Fix: add threadId? to handleNewSession and createSessionWithContext
options so callers can pass the Telegram topic ID at creation time.
createSession already includes platform.topicId in its initial
patchRecord({ immediate: true }) call, so the topicId is flushed to
disk atomically — no separate patchRecord needed.

Updated callers:
- telegram/commands/new-session.ts: 3 call sites
- telegram/commands/resume.ts: createSessionWithContext path
- core/assistant/assistant-manager.ts: pass threadId to createSession

Added regression tests documenting both the broken pattern (debounced
write loses topicId on crash) and the fixed pattern (included in
initial immediate save).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 16:27:38 +07:00
0xmrpeter
f9e36052ad fix: improve error handling in session prompt execution
- Updated the error handling in the Session class to emit a detailed error message when prompt execution fails, enhancing debugging and user feedback.
2026-04-03 16:13:47 +07:00
0xmrpeter
a6cf76f15e chore: bump version to 2026.403.6
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 15:51:51 +07:00
0xmrpeter
e193309e08 feat: enhance path validation and plugin configuration
- Added a new test to verify that allowedPaths can override ignore patterns for paths within the current working directory, ensuring proper access control for file uploads.
- Updated the path-guard logic to clarify that allowedPaths take precedence over ignore patterns.
- Simplified the plugin configuration logic for the Telegram channel by removing unnecessary mapping, directly importing the plugin when the channelId matches.
2026-04-03 15:50:24 +07:00
0xmrpeter
43c16dff4b chore: bump installer version to 1.0.2
- Updated the installer version in install.sh from 1.0.1 to 1.0.2 for consistency.
- Ensured shell configuration files are patched idempotently during Node.js installation, improving robustness across environments.
2026-04-03 15:13:18 +07:00
0xmrpeter
b55aa151db chore: bump installer version to 1.0.1
- Updated the installer version in both install.ps1 and install.sh scripts from 1.0.0 to 1.0.1, ensuring consistency across platforms.
2026-04-03 15:10:02 +07:00
0xmrpeter
f9c58cb2a2 fix: ensure ~/.zshrc exists before patching on macOS
- Updated the install.sh script to create ~/.zshrc if it does not exist, ensuring that the nvm installer can properly append necessary configurations.
- Enhanced the logic to patch both zsh and bash configuration files, improving the robustness of the installation process on macOS.
2026-04-03 15:09:30 +07:00
0xmrpeter
11a9e18bb0 chore: remove versioning from installer script commands in README and scripts
- Updated installation commands in README.md and scripts to remove version query parameters, simplifying the usage instructions for macOS, Linux, and PowerShell scripts.
2026-04-03 15:04:31 +07:00
0xmrpeter
fdf4fba7a3 chore: update installer scripts to version 1.0.0
- Modified installation commands in README.md to include versioning for macOS, Linux, and PowerShell scripts.
- Updated install.ps1 and install.sh scripts to define and display the installer version as 1.0.0, enhancing clarity for users.
2026-04-03 15:02:18 +07:00
0xmrpeter
aee454f2f7 refactor: enhance nvm installation script for macOS and PATH handling
- Simplified the logic for patching shell configuration files on macOS, ensuring ~/.zshrc is patched automatically and providing a safety net for other configurations.
- Improved PATH handling by skipping directories already present in the original PATH or within the nvm prefix, reducing unnecessary modifications.
- Added a user prompt to open a new terminal after nvm installation to ensure proper loading of nvm in the current session.
2026-04-03 14:58:37 +07:00
0xmrpeter
71411ca905 refactor: improve nvm shell configuration patching logic
- Enhanced the patch_nvm_shell_configs function to ensure nvm initialization lines are added to the appropriate shell configuration files based on the operating system.
- On macOS, it now always patches ~/.zshrc and checks for existing bash configurations, while on Linux, it patches existing files or creates ~/.bashrc if none are present.
- This change improves the robustness of the installation script by ensuring proper nvm setup across different environments.
2026-04-03 14:55:31 +07:00
0xmrpeter
ee4518af2e feat: add nvm shell configuration patching to install script
- Implemented a function to ensure nvm initialization lines are added to relevant shell configuration files (.bashrc, .zshrc, .bash_profile).
- The function checks for existing entries to avoid duplication and creates a .zshrc if none of the config files exist.
- This enhancement improves the user experience by ensuring nvm is properly set up across different shell environments on macOS.
2026-04-03 14:49:21 +07:00
0xmrpeter
ef9c6eabae chore: bump version to 2026.403.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 14:44:10 +07:00
0xmrpeter
23f2d295fd fix: add missing MenuItem/AssistantSection stubs to TestPluginContext
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 14:43:56 +07:00
0xmrpeter
7b2f0f78c1 chore: bump version to 2026.403.4
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 14:41:41 +07:00
0xmrpeter
eeb6a7d923 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-03 14:38:26 +07:00
0xmrpeter
18cc04d3f3 feat: implement file service path whitelisting for agents
- Added functionality to allow agents to read attachments from the file-service upload directory by whitelisting the base directory.
- Enhanced AgentInstance with addAllowedPath method to manage additional read paths.
- Updated SessionFactory to inject extra filesystem paths for agents, ensuring they can access necessary files without compromising workspace security.
- Refactored AgentSwitchHandler to utilize the file service for managing allowed paths during agent switching.

This change improves the flexibility of agent interactions with external files while maintaining security boundaries.
2026-04-03 14:38:16 +07:00
0xmrpeter
5329803b86 fix: Claude missing from onboarding list when Claude CLI not installed
The previous fallback wrote to a separate AgentStore instance, which saved
Claude to disk but left the in-memory AgentCatalog unaware of it. As a result,
catalog.getAvailable() did not include Claude, so it never appeared in the
onboarding agent multiselect.

Fix: add AgentCatalog.registerFallbackAgent() that writes directly into the
catalog's own store (this.store), making Claude immediately visible to
getAvailable() without requiring a reload.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 14:29:14 +07:00
0xmrpeter
aaf82863bb chore: bump version to 2026.403.3
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 14:15:47 +07:00
0xmrpeter
62cf9bd2bf fix: improve daemon restart logic and config management
- Added console log for stopping the daemon to enhance user feedback.
- Updated ConfigManager initialization to load from the specified config file.
- Refined the logic for determining the run mode, ensuring correct behavior when restarting a daemon based on its previous state.
2026-04-03 14:14:29 +07:00
0xmrpeter
46350a95c5 refactor: enhance API server port retrieval and adjust health check interval
- Updated API server port retrieval to use the service's getPort() method, ensuring accurate port assignment.
- Changed health heartbeat interval from 30 seconds to 15 seconds for more frequent health checks.
- Removed unnecessary DOMPurify script from file-viewer template to streamline loading for markdown rendering.
2026-04-03 13:58:41 +07:00
0xmrpeter
adbe268209 test: fix pre-existing api-server test failures to match current implementation
1. Health endpoint split: /health now returns only {status, uptime, version}
   (public, no auth). Sensitive details (memory, sessions, tunnel) moved to
   /health/details (requires auth + system:health scope). Split the single
   test into two — one for each endpoint. Also remove stale mockReturnValueOnce
   calls in the "allows health endpoint without auth" auth test that were never
   consumed and polluted the "accepts requests with valid auth token" test via
   Vitest's clearAllMocks not clearing the once-return queue.

2. Notify validation error: the error message changed from "Missing message" to
   "Required" (Zod default). Update the assertion to match.

3. SPA fallback bug fix (static-server.ts): the symlink traversal guard
   introduced in the security hardening commit broke SPA fallback for
   non-existent paths on macOS where /var is a symlink to /private/var.
   When realpathSync fails (file doesn't exist), the unresolved filePath starts
   with /var/... but realUiDir resolves to /private/var/..., so the prefix check
   fails and the static server returns false instead of serving index.html.
   Fix: skip the symlink guard when the file doesn't exist — a non-existent path
   cannot be a symlink pointing anywhere dangerous, so the guard is unnecessary.

4. Auth test pollution root cause: fixed by #1 — the old health test queued two
   mockReturnValueOnce values that were never consumed (new /health endpoint
   doesn't call listSessions/listRecords), so they leaked into the auth test
   which then got stale session data when calling the sessions route, causing
   s.clientOverrides to be undefined → TypeError → 500.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 13:37:37 +07:00
0xmrpeter
e90fedcef8 fix: properly clean up SSE connections and eventBus listeners on shutdown
- api-server: store SSEManager reference in plugin closure so teardown()
  can call sseManager.stop() before server.stop(); SSE connections use
  reply.hijack() and are not tracked by Fastify, so they must be
  explicitly closed to allow the server to release its port
- telegram: store session:threadReady and session:configChanged listener
  references as private fields and remove them in stop(); these were
  registered directly on core.eventBus (not via ctx.on) so ctx.cleanup()
  did not remove them, causing listener leaks on plugin restart

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 13:36:04 +07:00
0xmrpeter
9720330085 merge: resolve conflict in file-viewer.ts — keep sanitizeHtml version 2026-04-03 13:23:35 +07:00
Mr.Peter
ad83f7897c
Merge pull request #197 from Open-ACP/security-hardening
Security hardening: fix 15 vulnerabilities across agent sandbox, installer, plugin, and tunnel
2026-04-03 13:22:39 +07:00
0xmrpeter
637d326ea8 fix(api): enhance input validation and security measures across routes
- Implement Zod schemas for strict input validation on notify, tunnel, and topic routes.
- Block absolute workspace paths in CreateSession to prevent path injection.
- Validate scope strings and enforce limits on token lifetime and command strings.
- Sanitize output in file-viewer template to prevent XSS attacks.
- Adjust CORS settings and apply rate limiting for unauthenticated requests.
- Cap SSE connections and prompt body size to mitigate DoS risks.
- Restrict public health endpoint information to enhance security.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 13:22:26 +07:00
0xmrpeter
fa071dc5c4 fix: address code review findings — resolve critical, high, and medium issues
- C1: resolveWorkspace() now allows absolute/tilde paths under baseDir; rejects paths outside baseDir; update tests to match new semantics and add coverage for allowed cases
- C2: revert bore.ts to use --secret CLI flag instead of BORE_SECRET env var (bore does not support env var)
- H1: revert openacp.ts to use --token CLI flag instead of TUNNEL_TOKEN env var (cloudflared env var support unreliable)
- H2: add sessions:dangerous scope to KNOWN_SCOPES in roles.ts; not granted to any named role (admin-only via wildcard)
- H3: expand DEFAULT_ENV_WHITELIST with GIT_*, SSH_AUTH_SOCK/PID, terminal rendering vars; add comments documenting envWhitelist/allowedPaths config wiring as follow-up
- H4: revert tunnel viewer routes to auth: false — content is already gated by random UUIDs
- M1: readTextFile PathGuard rejection now throws Error instead of returning access-denied string as content
- M2: apply sanitizeHtml() to file-viewer fallback path (non-marked rendering) to prevent XSS
- M3: envWhitelist/allowedPaths documented as follow-up in agent-instance.ts comments
- M4: validateTarContents uses segment-based check for .. traversal to avoid false positives on filenames like setup..sh
2026-04-03 13:14:02 +07:00
0xmrpeter
fc69a2f122 security: harden API server and tunnel against injection and DoS attacks
Fix 26 vulnerabilities identified in security audit of the API server
plugin and public tunnel surface:

Input validation & injection prevention:
- Add Zod schemas with strict field limits to notify, tunnel, and topic routes
- Block absolute workspace paths in CreateSession to prevent path injection
- Validate scope strings with regex and cap at 20 scopes / 50 chars each
- Validate port range (1-65535) in tunnel POST and DELETE /:port
- Cap token lifetime to max 365 days; enforce max lengths on auth fields
- Cap command strings at 1000 chars; add max lengths to ID/name params

XSS prevention:
- Load DOMPurify CDN alongside marked.js in file-viewer template
- Sanitize marked.parse() output with DOMPurify before innerHTML assignment
- Escape HTML entities as fallback when DOMPurify is unavailable

CORS hardening:
- Remove Access-Control-Allow-Credentials: true from main server CORS
- Remove Access-Control-Allow-Credentials: true from SSE responses

Rate limiting:
- Add keyGenerator to extract real client IP from cf-connecting-ip /
  x-forwarded-for headers so rate limits work correctly behind tunnel proxies
- Apply per-route limit (5 req/min) on unauthenticated /auth/exchange

DoS & resource exhaustion:
- Cap SSE connections at 50; return 503 when limit is reached
- Cap prompt body at 100 KB (was unbounded)
- Add overall max lengths throughout all input schemas

Information disclosure:
- Public GET /health returns only {status, uptime, version}
- Move sensitive details (memory, sessions, adapters) to authenticated
  GET /health/details requiring system:health scope

Symlink traversal:
- Resolve realpathSync() before path prefix check in static-server.ts
  to prevent symlink-based path escapes out of the UI directory

Token leakage:
- Log a warning (with token redacted) when auth token is passed via URL
  query param instead of Authorization header to catch accidental logging

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 13:12:38 +07:00
0xmrpeter
b1840d538d test: update tests to match new security behavior (reject unsafe paths, no description auto-approve)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:38:28 +07:00
0xmrpeter
f33f89223a fix: tunnel auth default on, XSS sanitization, credential env vars, path redaction
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:36:23 +07:00
0xmrpeter
3919d29c12 feat: add lightweight HTML sanitizer for tunnel viewer XSS prevention
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:34:58 +07:00
0xmrpeter
8a9a724b15 fix: add download size limit and tar validation to install-binary 2026-04-03 12:32:52 +07:00
0xmrpeter
6e0cde1e41 fix: add --ignore-scripts to all npm install calls to prevent lifecycle RCE 2026-04-03 12:31:28 +07:00
0xmrpeter
ae6a904789 feat: add checksum verification, size limits, path validation to agent installer
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:30:02 +07:00
0xmrpeter
7f75153a4c fix: require sessions:dangerous scope for bypass permissions endpoint
The /dangerous endpoint previously accepted any sessions:write token, allowing
any write-authorized API client to toggle bypass permissions. It now requires
the dedicated sessions:dangerous scope to restrict this capability to explicitly
authorized clients.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:27:00 +07:00
0xmrpeter
a8217ea535 fix: remove description-based auto-approve bypass in session-bridge
Agents could craft tool descriptions containing "openacp" to bypass all
permission gates. Remove the string-match check entirely; the only
legitimate auto-approve path is now the explicit bypass mode (agent
bypassPermissions config or client clientOverrides.bypassPermissions).

Update tests to assert that "openacp" in a description no longer
auto-approves requests when bypass mode is off.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:25:27 +07:00
0xmrpeter
2bb70d0ac9 feat: wire PathGuard and EnvFilter into agent file operations and process spawning
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:23:57 +07:00
0xmrpeter
e8a0242e72 feat: add workspace.security config schema and fix resolveWorkspace path traversal
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:21:22 +07:00
0xmrpeter
ace8d675d8 feat: add EnvFilter module to prevent environment variable leakage
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:19:11 +07:00
0xmrpeter
59c76a080b feat: add PathGuard module for workspace boundary enforcement
Implements PathGuard with symlink resolution, default deny patterns for
sensitive files (.env, *.key, credentials*), allowedPaths support, and
custom ignore pattern overrides via constructor options.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:17:14 +07:00
0xmrpeter
07daa1d432 chore: add ignore package for .openacpignore support 2026-04-03 12:14:23 +07:00
0xmrpeter
f9bcb34979 fix(viewer): skip binary files and downgrade spurious WARN for out-of-workspace paths
When an agent reads a voice attachment saved to ~/.openacp/files/ (e.g. after
a Telegram voice message), the viewer-store logged a WARN "Path outside
workspace, rejecting" for every such read. This was misleading — the rejection
only affected viewer link generation, not the actual file access — but it made
the STT feature appear broken.

Two fixes:

1. message-transformer: skip binary/non-text file extensions (.wav, .ogg, .mp3,
   .mp4, .jpg, .png, .pdf, .zip, etc.) before attempting to generate viewer
   links. Binary files cannot be displayed in the code viewer, so calling
   storeFile/storeDiff for them was always pointless.

2. viewer-store: downgrade the path-outside-workspace log from WARN to DEBUG.
   Returning null for out-of-workspace paths is expected, not an error.

Fixes #195

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 11:15:05 +07:00
0xmrpeter
cb7e587382 chore: bump version to 2026.403.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 10:58:07 +07:00
0xmrpeter
78495c7856 fix: always show Claude Agent in onboarding list when Claude CLI is missing
When the Claude CLI (`claude` command) is not installed, `installAgent()`
fails the dependency check and returns `{ ok: false }` without adding the
agent to the store. The previous code ignored this return value, so the
fallback path (direct store.addAgent) was never reached, leaving Claude
absent from the onboarding agent selection list entirely.

Fix: check the install result and fall through to the bundled fallback when
the registry install fails for any reason.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 10:56:26 +07:00
0xmrpeter
8b9b7ffc36 fix(channels): read config from plugin settings instead of config.channels
After the plugin system migration, channel configuration (botToken, chatId,
etc.) is stored in SettingsManager (~/.openacp/plugins/data/) rather than
in config.channels. Several UI and diagnostic code paths still read from
the old location, causing channels to always appear as "Not configured"
even after a successful setup.

Fixes #194

Changes:
- getChannelStatuses(): make async, check SettingsManager before config.channels
- configureChannels(): accept settingsManager param, use it for status display
  and when invoking plugin configure()
- editChannels(): check SettingsManager for configured/enabled display status
- editDiscord(): fix wrong SettingsManager basePath (plugins → plugins/data)
- summarizeConfig(): make async, check SettingsManager for channel status
- telegramCheck (openacp doctor): read botToken/chatId from plugin settings
  first, fall back to legacy config.channels
- config.ts cmdConfig: fix SettingsManager basePath (plugins → plugins/data)
- onboard.ts cmdOnboard: pass settingsManager to runReconfigure()
- runReconfigure(): accept and propagate settingsManager to sub-functions

Tests: add setup-channels, helpers, and telegram-check unit tests covering
the plugin-settings-first read behavior.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 10:55:38 +07:00
0xmrpeter
93c5aea626 fix(install): auto-detect and install Xcode CLT on macOS before nvm 2026-04-03 10:39:34 +07:00
Mr.Peter
6b4867854d
Merge pull request #196 from Open-ACP/develop
chore: merge develop into main
2026-04-03 10:29:30 +07:00
0xmrpeter
4480389b65 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-03 10:27:05 +07:00
0xmrpeter
e300e7d605 refactor(docs): update installation instructions and requirements in README; modify Node.js version check in install scripts 2026-04-03 10:26:57 +07:00
0xmrpeter
e359613e07 chore: bump version to 2026.403.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 10:05:25 +07:00
0xmrpeter
1f071db03a Merge branch 'develop' of github.com-peter:Open-ACP/OpenACP into develop 2026-04-03 10:04:45 +07:00
0xmrpeter
eea6e9a4fe fix: update tests for current API and add config value-type validation
- Add TypedEmitter to mock AgentInstance (Session constructor requires .on())
- Update config-migrations test for cloudflare→openacp tunnel provider migration
- Add missing mock fields (api, agentCatalog, settingsManager, setPath)
- Isolate instance-context tests from OPENACP_INSTANCE_ROOT env var
- Fix SSE tests to read past initial `: connected` comment
- Add validateFieldValue() to config-registry for type-safe config writes
- Handle ConfigValidationError in API error handler (→ 400)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:03:53 +07:00
0xmrpeter
ed3256a283 feat(conversation-history): implement conversation history tracking with middleware and type definitions 2026-04-03 09:54:37 +07:00
0xmrpeter
d9b93b3542 test: update instance-copy tests for migrated section stripping 2026-04-03 09:49:18 +07:00
0xmrpeter
378b97d3d0 fix: config editor routes edits to plugin settings for migrated fields
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:47:26 +07:00
0xmrpeter
73b6d58b20 fix: correct inheritableKeys to match actual plugin setting keys
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:46:11 +07:00
0xmrpeter
0a91c37f28 fix: speech hot-reload reads from plugin settings, emit synthetic config:changed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:46:05 +07:00
0xmrpeter
36cdf4ce1c fix: env var overrides now flow to plugin settings
Add ConfigManager.applyEnvToPluginSettings() that maps env vars like
OPENACP_TUNNEL_ENABLED and OPENACP_TELEGRAM_BOT_TOKEN to the correct
plugin settings keys, and call it from main.ts after config load.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:43:57 +07:00
0xmrpeter
92ac54a3c3 fix: instance-copy strips migrated plugin sections from config.json
Remove security, tunnel, api, speech, usage sections and plugin-owned
channel fields when copying an instance, preventing lifecycle-manager
fallback from leaking unfiltered settings to the new instance.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:35:15 +07:00
0xmrpeter
377e84c6f3 fix: Telegram /settings reads/writes plugin settings for migrated fields
Replace getConfigValue/configManager.save() with getFieldValueAsync/
setFieldValueAsync so that fields with a plugin scope (tunnel, security,
speech) are read from and written to plugin settings instead of config.json.
Also make buildSettingsKeyboard async and fix speech.stt.provider API key
check to read groqApiKey from plugin settings when SettingsManager is available.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:33:15 +07:00
0xmrpeter
5179d3334d fix: API config route reads/writes plugin settings for migrated fields
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:31:33 +07:00
0xmrpeter
aebd7fa8d8 fix: SecurityGuard reads live from SettingsManager, checkAccess now async
SecurityGuard no longer takes ConfigManager directly. Instead it receives
a getSecurityConfig() async accessor that reads from SettingsManager on
each checkAccess call, so runtime settings changes take effect immediately.

- Export SecurityConfig interface for type-safe config access
- Fix inheritableKeys to match actual settings keys
- Update core.ts to await the now-async checkAccess
- Rewrite tests for new async API with full coverage

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:29:55 +07:00
0xmrpeter
3c74ec0feb feat: add plugin mapping to config registry with async read/write helpers
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:25:41 +07:00
0xmrpeter
32132a801e fix(api-server): use singleton RegistryClient to enable 1-min TTL cache 2026-04-03 01:20:34 +07:00
0xmrpeter
a031d21f6e fix(api-server): move GET /marketplace before parameterized routes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 01:04:43 +07:00
0xmrpeter
b92e542a30 feat(api-server): register /api/v1/plugins route group
Wire lifecycleManager into RouteDeps and register pluginRoutes at
/api/v1/plugins alongside the existing route plugins.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 00:35:41 +07:00
0xmrpeter
d676faadc7 fix(api-server): fix decodeURIComponent, static node imports, assert enable test spies 2026-04-03 00:33:33 +07:00
0xmrpeter
3d39d1d811 fix(test): mock RegistryClient to make marketplace tests reliable
Replace network-dependent 503 assumption with vi.mock of registry-client,
enabling deterministic happy-path (200) and error-path (503) tests regardless
of internet availability in the test environment.
2026-04-03 00:29:32 +07:00
0xmrpeter
4648ae50a1 feat(api-server): add DELETE /plugins/:name endpoint 2026-04-03 00:27:45 +07:00
0xmrpeter
c3e4e32a9b feat(api-server): add POST /plugins/:name/disable endpoint 2026-04-03 00:27:09 +07:00
0xmrpeter
f731f30b9a feat(api-server): add POST /plugins/:name/enable endpoint 2026-04-03 00:26:30 +07:00
0xmrpeter
2a72a1ee38 feat(api-server): add GET /plugins/marketplace endpoint 2026-04-03 00:24:07 +07:00
0xmrpeter
3526752bb3 chore: remove unused beforeEach import in routes-plugins test 2026-04-03 00:22:47 +07:00
0xmrpeter
cea1009e6c feat(api-server): add GET /plugins endpoint
Implements GET /api/v1/plugins route that lists all installed plugins
with runtime state (loaded, failed, essential, hasConfigure) merged
from the plugin registry and LifecycleManager.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 00:20:24 +07:00
0xmrpeter
d180967d17 feat(api-server): add lifecycleManager to RouteDeps 2026-04-03 00:17:22 +07:00
0xmrpeter
87cec6734a feat(lifecycle): expose plugins and instanceRoot as public getters 2026-04-03 00:14:48 +07:00
0xmrpeter
81d2184f4d docs: add plugins API spec and implementation plan
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 00:12:35 +07:00
0xmrpeter
79aee6960f refactor: simplify SSE connection logging
- Updated logging for new connections and closed connections to remove session ID details, focusing on total connection counts for clarity.
2026-04-02 22:00:56 +07:00
0xmrpeter
6743e10af3 chore: bump version to 2026.402.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:50:44 +07:00
0xmrpeter
3a01a50949 feat: enhance CLI instance commands and add POST /exchange route
- Updated CLI to register `instances` in `noInstanceCommands` map, allowing access without an existing instance root.
- Refactored instance creation to use `generateSlug` instead of `slugify`.
- Added `POST /exchange` route in the API server for exchanging one-time codes for JWTs, ensuring proper authentication bypass handling.
- Improved error handling for port detection in the API server, simplifying retry logic for available ports.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:46:31 +07:00
0xmrpeter
72f99a3a62 refactor: make tunnel plugin self-contained, remove inheritableKeys
Plugin no longer reads from config.json via inheritableKeys. Instead:
- setup() bootstraps settings.json with openacp defaults if missing
- Migration in setup() handles existing cloudflare users by rewriting settings.json
- Single source of truth: plugins/data/@openacp/tunnel/settings.json

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:22:50 +07:00
0xmrpeter
bd5341995e feat: auto-migrate tunnel provider from cloudflare to openacp
Existing users with provider: 'cloudflare' will be automatically
migrated to 'openacp' on next startup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:09:30 +07:00
0xmrpeter
26b78cf28f feat: set production API key for OpenACP tunnel worker
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:08:13 +07:00
0xmrpeter
3d36553cac Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 20:42:11 +07:00
Mr.Peter
8255a41eec
Merge pull request #193 from Open-ACP/feat/openacp-managed-tunnel
feat: OpenACP managed tunnel provider
2026-04-02 20:39:11 +07:00
0xmrpeter
ff29e9e29f fix: disable TCP Nagle algorithm for SSE connections
Small SSE chunks (like heartbeats) were being buffered by TCP until
a full packet was assembled. socket.setNoDelay(true) forces immediate
send, which is required for SSE to work through Cloudflare tunnel.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:40:54 +07:00
0xmrpeter
2d09b32b96 fix: flush SSE stream immediately for Cloudflare tunnel compatibility
Cloudflare buffers SSE responses until it receives initial data.
Send a ':connected' comment immediately after writeHead/flushHeaders
so the stream is flushed through the proxy to the client.

Also reduce heartbeat from 30s to 15s to prevent Cloudflare idle timeout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:30:30 +07:00
0xmrpeter
a904c14686 debug: add SSE connection logging (new connection, close, count)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:26:04 +07:00
0xmrpeter
f321f44bc8 fix: restore CORS headers via onRequest hook
Removed @fastify/cors but forgot to restore CORS headers, breaking
cross-origin requests from the Tauri WebView (localhost:1420) to
remote tunnel URLs. Add a lightweight onRequest hook that mirrors
the previous allow-all-origins behavior.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:21:14 +07:00
0xmrpeter
71270591b4 chore: remove @fastify/cors dependency
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:02:37 +07:00
0xmrpeter
bf0b709f78 refactor: remove @fastify/cors — token auth makes it redundant
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:02:00 +07:00
0xmrpeter
967d4cfece fix: allow SSE to work through Cloudflare tunnel and non-localhost origins
SSE (sse-manager.ts):
- Allow any origin in CORS headers — endpoint is auth-protected via token
- Add X-Accel-Buffering: no to prevent proxy/Cloudflare from buffering the stream
- Add no-transform to Cache-Control to prevent content transformation

CORS (server.ts):
- Allow all origins globally — token-based auth makes origin restrictions redundant
  and blocking non-localhost origins breaks tunnel access from Tauri WebView

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 19:01:23 +07:00
0xmrpeter
0def26e882 fix: return 200 with null history instead of 404 for sessions without history 2026-04-02 18:40:51 +07:00
0xmrpeter
f4b2943316 fix: address code review issues — subdomain race condition, cron pagination, tests
Worker:
- create.ts: reserve subdomain before CF API calls as optimistic lock, release on failure
- cron.ts: paginate KV list (was capped at 1000 keys, now handles any count)
- rate-limit.ts: document non-atomicity trade-off more explicitly
- wrangler.toml: add deployment instructions for KV namespace IDs

Core:
- openacp.ts: add TODO for API key placeholder, clarify --url flag usage, document
  15s startup timeout rationale, log CF API warnings from DELETE response
- tunnel-service.ts: document why cloudflare fallback is at TunnelService layer
- openacp-provider.test.ts: add tests for stop(force), heartbeat interval, 429 error

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:27:23 +07:00
0xmrpeter
6d32160d4c feat: wire OpenACPTunnelProvider into registry, set as default, add cloudflare fallback
- TunnelRegistry: add PluginStorage field, openacp case in createProvider(), update default fallback
- TunnelService: accept storage param and forward to registry; add cloudflare fallback when openacp fails
- TunnelConfig schema: add 'openacp' to provider enum, set as default
- Tunnel plugin index: add storage permissions, pass ctx.storage to TunnelService, update install/configure provider selects with openacp as first option
2026-04-02 18:15:31 +07:00
0xmrpeter
bde5a1071e fix: mock commandExists in provider tests, add startup log 2026-04-02 18:12:25 +07:00
0xmrpeter
84c4a0f438 feat: instances CLI, auth code exchange, workspace endpoint 2026-04-02 18:10:52 +07:00
0xmrpeter
ca4e789925 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 18:10:52 +07:00
0xmrpeter
537cc37b1a test: add missing tests for expired code and instances CLI flows
auth-exchange.test.ts:
- Add 'returns 401 for expired code' test — creates a code, mocks
  Date.now() past the default 30-minute TTL, verifies the exchange
  endpoint returns 401. Uses vi.spyOn(Date, 'now') instead of
  vi.useFakeTimers() to avoid blocking Fastify's async I/O.

instances-cli.test.ts:
- Add '.openacp exists but not in registry → registers it' test —
  mocks fs.existsSync to return true, registry.getByRoot to return
  undefined, verifies register() and save() are called.
- Add '--no-interactive creates minimal config' test — mocks
  fs.existsSync to return false, verifies mkdirSync is called on
  instanceRoot, config.json is written with instanceName and runMode,
  plugins.json is written, and registry.register/save are called.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:09:17 +07:00
0xmrpeter
6d631d3966 fix(cli): instances.ts — three code review fixes
Fix 1 (IMPORTANT): Use jsonError() for error paths in cmdInstancesCreate
when --json flag is active. Missing --dir and already-registered cases
now call jsonError() before the console.error/process.exit path.

Fix 2 (IMPORTANT): Move wantsHelp(args) check to the very top of
cmdInstances() so `openacp instances --help` is handled before the
subcommand dispatch, preventing it from falling through to "Unknown
subcommand" error.

Fix 3 (MINOR): Move fs.mkdirSync(instanceRoot) inside each branch
(--from, --no-interactive, interactive) to avoid leaving an orphaned
empty directory if copyInstance throws or config write fails.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:07:55 +07:00
0xmrpeter
2e3c1f7007 feat(cli): extend default.ts --json output with name, directory, port
Mirror the same extended JSON output shape from start.ts into default.ts
for both the daemon start path and the foreground start path.

Output shape: { success: true, data: { pid, instanceId, name, directory, dir, port } }

- Imports isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes
- Daemon path: resolves instanceId from registry, reads api.port file,
  falls back to config.api.port, calls jsonSuccess with full payload
- Foreground path: outputs JSON with process.pid before starting server
- Error path: calls jsonError(DAEMON_NOT_RUNNING, ...) in JSON mode

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:07:45 +07:00
0xmrpeter
7d263a0e7e feat: add OpenACPTunnelProvider with tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 18:04:28 +07:00
0xmrpeter
013fe12e19 chore: bump version to 2026.402.4
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:42:19 +07:00
0xmrpeter
fc41d74ab1 feat: add GET /api/v1/workspace endpoint
Expose workspace identity (id, name, directory, version) via a new
authenticated REST endpoint for CLI and client tooling to discover
which OpenACP instance they are connected to.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:17:35 +07:00
0xmrpeter
cc3897764d feat: add POST /auth/exchange for one-time code to JWT
Adds dedicated test suite for the exchange endpoint, covering valid
code success, invalid code rejection, and already-used code rejection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:14:06 +07:00
0xmrpeter
077a254ba4 feat: extend start --json output with name, directory, port
Extend the JSON output of `openacp start --json` to include `name`
(from config.instanceName), `directory` (path.dirname of root),
and `port` (from api.port file or config fallback). The `dir` field
is kept for backward compatibility. instanceId is resolved from the
instance registry when available, falling back to path.basename(root).
2026-04-02 17:11:40 +07:00
0xmrpeter
dbc4d3fbfc chore: bump version to 2026.402.3
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:11:38 +07:00
0xmrpeter
bcaa61b969 chore: remove unused dependencies from package.json and pnpm-lock.yaml
- Deleted '@inquirer/prompts', 'p-queue', and 'shiki' from both package.json and pnpm-lock.yaml to streamline the project and reduce bloat.
2026-04-02 17:11:08 +07:00
0xmrpeter
3a45d8a209 feat: register instances subcommand in CLI
Add cmdInstances to the noInstanceCommands object so it reads directly
from the global registry without requiring an existing instance root.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:09:37 +07:00
0xmrpeter
eb09ffd6d8 feat: add instances create command
Implement cmdInstancesCreate with support for --dir (required), --from (copy existing instance), --name, --agent, and --no-interactive flags. Handles three cases: .openacp already registered (error), .openacp exists but unregistered (register it), and fresh creation (write minimal config).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:06:41 +07:00
0xmrpeter
ded47458a7 feat: add instances list command with --json output
Implements `openacp instances list` command with buildInstanceListEntries
helper that maps the InstanceRegistry to InstanceListEntry objects with
status/port/directory fields. Adds 4 passing unit tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 17:01:54 +07:00
0xmrpeter
695dd1c6fe docs: add implementation plan for instances CLI and auth exchange
Covers: instances list/create commands, start --json extension,
POST /auth/exchange endpoint, GET /api/v1/workspace route.
TDD with vitest, step-by-step with exact code and commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:40:42 +07:00
0xmrpeter
b5d24bce5a chore: bump version to 2026.402.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:32:50 +07:00
0xmrpeter
e558b477e4 Merge branch 'develop' of github.com-peter:Open-ACP/OpenACP into develop 2026-04-02 16:29:19 +07:00
0xmrpeter
90d637348e fix: /menu command shows dynamic button keyboard in Telegram
- Add 'menu' to TELEGRAM_OVERRIDES so /menu triggers the rich button
  keyboard handler instead of the generic text-based CommandRegistry response
- handleMenu now accepts optional menuRegistry so it shows plugin-contributed
  menu items (same keyboard as the welcome message)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:28:07 +07:00
0xmrpeter
56e79875fe Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 16:25:20 +07:00
0xmrpeter
0c302331cc docs(cli): enhance help documentation with --json flag support
- Added `--json` flag descriptions to various CLI commands in the help text.
- Updated command usage examples to include `--json` for machine-readable output.
- Clarified that commands supporting `--json` will output results in a consistent JSON format.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:24:54 +07:00
0xmrpeter
9c74a3e9e0 docs: revise instances CLI and auth codes spec
- Clarify instances list vs status --all distinction
- Fix --from flag convention (parent dir, not .openacp subdir)
- Extend start --json output spec to include name/directory/port
- Clarify --json on onboarding: controls output format, not interactivity
- Fix CLI registration files: src/cli.ts + src/cli/commands/index.ts
- Add note on backward compat: keep dir field in start --json output

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:22:35 +07:00
0xmrpeter
7b768c717d docs: add spec for instances CLI and auth code exchange
Spec for two core additions supporting the Add Workspace app feature:
- `openacp instances list/create` CLI subcommands with --json output
- Auth code exchange endpoints (POST /auth/codes, POST /auth/exchange)
- GET /api/v1/workspace endpoint for workspace identity info

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:17:16 +07:00
0xmrpeter
a2ac1d2ac4 feat(instance): use UUID instead of slug for instance IDs
New instances created via setup wizard now get a UUID as their ID
instead of a slug derived from the instance name. This guarantees
uniqueness across instances without collision handling.

- wizard.ts: use randomUUID() instead of generateSlug + uniqueId
- default.ts / restart.ts: look up existing registry entry first,
  fall back to a fresh UUID for unregistered instances
- cli.ts: replace 'unknown' fallback with randomUUID()
- main.ts: look up registry before falling back to randomUUID()

Existing instances with slug/hardcoded IDs remain fully compatible —
the registry lookup ensures their stored IDs are reused on subsequent
starts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:15:44 +07:00
0xmrpeter
709adad68f Merge branch 'develop' of github.com-peter:Open-ACP/OpenACP into develop 2026-04-02 15:46:32 +07:00
0xmrpeter
a9d82ebd2f feat: enhance welcome message to include workspace information
- Updated the welcome message to display the user's workspace path.
- Modified the assistant manager to defer system prompts until the first user message.
- Adjusted the Telegram adapter to prepend any pending system prompts to user messages.

This improves user context and interaction clarity upon starting a session.
2026-04-02 15:46:25 +07:00
0xmrpeter
51ead8c94b refactor: move New Session button flow intercept to adapter
Core menu item reverted to generic 'delegate' action — works for all
adapters. Telegram adapter intercepts 'core:new' in the delegate case
to show its button-driven flow instead of delegating to AI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:43:38 +07:00
0xmrpeter
e49d6993b1 fix: New Session flow sends new message, keeps menu untouched
Menu message is never edited — stays visible for future actions.
Agent picker sends a NEW message. Subsequent steps (workspace picker,
creating, success) edit that message in-place.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:41:51 +07:00
0xmrpeter
3cf4d852f6 fix: New Session flow edits same message instead of creating new ones
- All steps (agent picker → workspace picker → creating → success)
  now edit the same message in-place
- Success state shows deep link to open the new session topic
- Error state shows failure message with retry hint
- Custom path step updates message before delegating to AI
- Cross-platform path shortening using process.env.HOME

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:36:31 +07:00
0xmrpeter
943f8ab26c chore: move spec and plan to docs/superpowers/ 2026-04-02 15:27:55 +07:00
0xmrpeter
16f92a7e27 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 15:26:33 +07:00
0xmrpeter
16a40c7993 fix: escape HTML entity in help text
<name> was parsed as HTML tag by Telegram, causing parse error.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:19:21 +07:00
0xmrpeter
673e914b28 fix: Back to Menu button now shows full menu from MenuRegistry
s:back handler was calling buildMenuKeyboard() without menuRegistry,
showing only 5 hardcoded buttons. Now passes menuRegistry for the
complete dynamic menu.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:18:55 +07:00
0xmrpeter
466221a124 feat(cli): standardize --json output across all CLI commands
Add --json flag support to all data/query and action/result CLI commands.
Consistent envelope: { success, data } / { success, error: { code, message } }.

Commands: version, agents (list/info/install/uninstall), plugins (list/search/enable/disable/install/uninstall),
status, config set, start, stop, restart, doctor, tunnel (add/list/stop/stop-all),
adopt, remote, api (20+ subcommands), legacy install/uninstall.

Breaking: agents list --json and setup --json output format changed to new envelope.
2026-04-02 15:15:24 +07:00
0xmrpeter
3caaa5c397 test(cli): add integration tests for api and legacy install/uninstall --json
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:12:58 +07:00
0xmrpeter
672b7635ca test(cli): add integration tests for config set, adopt, restart --json
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:11:09 +07:00
0xmrpeter
46fadb72fe fix(cli): address code review issues for --json implementation
- Add muteForJson() to version command
- Fix wrong error code in setup.ts (MISSING_ARGUMENT → CONFIG_INVALID)
- Use ErrorCode type in jsonError signature for type safety
- Add process.exit re-throw guards to adopt.ts and remote.ts
- Remove dead return statements after jsonError calls
- Fix any types in doctor.ts
- Update spec for apiPort/tunnelPort naming

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:08:52 +07:00
0xmrpeter
09627a0eeb docs(cli): add --json flag to help text for all supported commands
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:51:04 +07:00
0xmrpeter
e919bb7223 fix: address code review issues in New Session flow
- Add TTL-based workspace cache eviction (5min, max 50 entries)
- Remove (r: any) cast, use typed SessionRecord
- Resolve baseDir for comparison with absolute paths in records
- Use process.env.HOME for cross-platform path shortening

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:50:46 +07:00
0xmrpeter
f57ece81ae chore: re-export TELEGRAM_OVERRIDES from commands index
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:46:35 +07:00
0xmrpeter
f98647eaa3 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.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:46:10 +07:00
0xmrpeter
fca3e82737 feat(cli): add --json support to api command (all subcommands)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:46:09 +07:00
0xmrpeter
64ef8f83ab fix: menu buttons dispatch to rich Telegram handlers
- Command type: intercept map routes Agents, Sessions, Doctor, Update,
  Restart, Help to Telegram handlers with inline keyboards
- Callback type: Settings button (s:settings) now calls handleSettings
- Refresh button (m:topics) now calls handleTopics directly

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:44:05 +07:00
0xmrpeter
4259ba76ea feat(cli): add --json support to plugin install/uninstall and legacy install/uninstall
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:44:03 +07:00
0xmrpeter
b15af4abe0 feat(cli): add --json support to config set, adopt, remote
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:43:53 +07:00
0xmrpeter
78033e81c1 feat: intercept slash commands for Telegram-specific handlers
Add TELEGRAM_OVERRIDES map that routes /agents, /sessions, /doctor,
/update, /restart, /help to rich Telegram handlers with inline
keyboards instead of generic CommandRegistry core responses.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:42:19 +07:00
0xmrpeter
5dba1746a5 feat(cli): add --json support to agents install, uninstall, info
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:41:18 +07:00
0xmrpeter
fdf9ae990f feat(cli): add --json support to doctor command (implies --dry-run)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:40:30 +07:00
0xmrpeter
7fe7869cad Add implementation plan: menu button & command dispatch fix
8 tasks covering: intercept map, slash command intercept, m: handler
fixes (command + callback types), m:topics refresh, New Session
button flow with ns: prefix callbacks, and manual smoke test.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:38:48 +07:00
0xmrpeter
d3a690294b feat(cli): add --json support to plugins, plugin search, plugin enable/disable
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:36:28 +07:00
0xmrpeter
3a254e58c7 feat(cli): add --json support to start, stop, restart commands
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:36:18 +07:00
0xmrpeter
5dfac08605 Fix spec: callback data size limit, ns: dispatch flow
- Workspace paths use numeric cache IDs instead of base64 in callback
  data (Telegram 64-byte limit)
- Clarify that m: handler must call ns: logic directly since grammY
  cannot re-dispatch callbacks
- Add explicit callback case handling for both s:settings and ns:start

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:35:53 +07:00
0xmrpeter
27c4229f55 feat(cli): add --json support to status command
Also fix pre-existing type error in stop.ts (result.error possibly undefined).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:35:44 +07:00
0xmrpeter
fbec2ce94f refactor(cli): migrate agents list and setup to standardized --json envelope
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:32:30 +07:00
0xmrpeter
2caeb4f750 Add spec: menu button & command dispatch fix
Addresses broken menu buttons (Settings, Update, Doctor), degraded UX
(Sessions, Agents, Help), and adds button-driven New Session flow.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:32:12 +07:00
0xmrpeter
481a0e3921 feat(cli): add --json support to version command
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:31:18 +07:00
0xmrpeter
b7bab6703b test(cli): add JSON output test utilities
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:29:52 +07:00
0xmrpeter
e8aa355516 feat(cli): add standardized JSON output helpers (output.ts)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 14:29:45 +07:00
0xmrpeter
a843413c65 docs: add CLI --json output design spec and implementation plan 2026-04-02 14:27:00 +07:00
0xmrpeter
3af41aec5b chore: bump version to 2026.402.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 12:56:59 +07:00
0xmrpeter
9b8239373a feat(setup): enhance channel configuration and desktop app detection
- Preserve existing channels and ensure the SSE adapter is enabled during setup.
- Update configuration schema to provide a default for channels.
- Implement desktop app detection for the SSE channel, checking common installation paths across platforms.
- Adjust setup integrations to remove unnecessary config parameter and streamline integration checks.
- Update wizard to include desktop app in channel options and handle installation prompts accordingly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 12:55:11 +07:00
0xmrpeter
09113d5a21 feat(commands): implement real /switch command with agent menu
/switch now resolves session, shows available agents as menu, and
performs agent switch directly. /switch label on|off persists config.
Removes delegation to adapter-specific silent handlers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:40:51 +07:00
0xmrpeter
ad52f755e0 feat(telegram): render menu and confirm command responses as inline keyboards
Adds callback rendering for CommandResponse types 'menu' (inline buttons)
and 'confirm' (yes/no buttons). Also improves session factory log for
skipped error/cancelled sessions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:38:41 +07:00
0xmrpeter
03f150613f fix(commands): fix dangerous mode bypass detection, remove duplicate /bypass
Bypass state now checks BOTH agent mode config and client override.
Removed redundant /bypass command from security plugin (already handled
by /dangerous).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:38:33 +07:00
0xmrpeter
485c64b5de feat(commands): add /archive command to stop agent and delete topic
Adds confirmation flow before archiving. Validates session state and
prevents archiving sessions still initializing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:38:24 +07:00
0xmrpeter
3357507160 feat(commands): implement real /agents list and /install menu
/agents now shows installed and available agents from AgentCatalog.
/install with no args shows interactive menu of installable agents.
/install <name> delegates to assistant for guided install flow.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:38:16 +07:00
0xmrpeter
cbc3214b13 fix(sessions): add immediate flush option to session store writes
Session records created during createSession() must be persisted to disk
immediately (not debounced) so they survive crashes before the next
debounce cycle. Adds flush() to SessionStore interface and immediate
option to patchRecord(). Also flushes on shutdown/destroyAll.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:38:08 +07:00
0xmrpeter
b9120ba82e fix(api-server): address PR #189 review — security, encapsulation, error handling
- Revert SessionIdParamSchema regex that was a breaking change for all session routes
- Add path traversal protection in HistoryStore.filePath() using path.basename()
- Remove decodeURIComponent bypass risk in history route
- Add ServiceUnavailableError class for consistent 503 error handling
- Refactor: route history access through ContextManager.getHistory() instead of
  exposing internal HistoryStore as standalone service
- Add path traversal and ContextManager.getHistory() tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:27:21 +07:00
lngdao
f35b6d130b fix(api-server): address PR #189 review — session check, path traversal, 503 status
- Add session existence check before querying history store
- Add regex constraint to SessionIdParamSchema to prevent path traversal
- Return 503 instead of 404 when history store is unavailable
2026-04-02 11:27:21 +07:00
lngdao
b4d78d511f feat(api-server): add session history endpoint
GET /api/v1/sessions/:sessionId/history returns the full conversation
history for a session from the context plugin's HistoryStore.
2026-04-02 11:27:21 +07:00
0xmrpeter
17f6a4ec92 feat(session): buffer latest commands for agent events before bridge connection
- Added a mechanism to store the latest commands emitted by the agent in the Session class, ensuring they are not lost before the SessionBridge connects.
- Implemented replay of buffered commands upon bridge connection to maintain continuity in command handling.
2026-04-02 11:08:11 +07:00
Mr.Peter
0fed71db58
Merge pull request #191 from Open-ACP/develop
Develop
2026-04-02 11:00:23 +07:00
0xmrpeter
602ea7b620 fix(cli): validate runMode flag, improve test tmpDir lifecycle
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 02:18:30 +07:00
0xmrpeter
875a1a2b54 fix(cli): remove extra channels field, add autoStart assertion in setup tests 2026-04-02 02:15:40 +07:00
0xmrpeter
ae7a7b726b feat(cli): add non-interactive openacp setup command
Adds `openacp setup` command for programmatic configuration by the desktop app, accepting --workspace, --agent, --run-mode, and --json flags.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 02:11:43 +07:00
0xmrpeter
d78c1454c2 fix(cli): normalize agents --json test mock pattern and remove undocumented switch case
- Remove case "--json": from switch statement in agents.ts to prevent undocumented behavior like "openacp agents --json gemini" silently misbehaving. The "list" and "undefined" cases are sufficient.
- Update test 2 to use ['list', '--json'] instead of ['--json'] now that the undocumented case is removed.
- Normalize mock pattern to use standard vi.fn().mockImplementation() with class syntax for better maintainability.
- Add afterEach(() => vi.restoreAllMocks()) to ensure proper cleanup between tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 02:09:40 +07:00
0xmrpeter
d361c2f69b feat(cli): add --json flag to openacp agents list
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 02:06:41 +07:00
0xmrpeter
e5bf0f39a1 Merge remote-tracking branch 'origin/develop' into develop 2026-04-02 00:59:31 +07:00
0xmrpeter
77f658121d feat(channel): add onSessionCreated hook for session initialization
- Introduced the onSessionCreated method in the IChannelAdapter interface to allow adapters to send initial and control messages after a session is fully created.
- Updated OpenACPCore to notify the adapter when a session is ready.
- Implemented onSessionCreated in the TelegramAdapter to send initial setup messages and control options upon session creation.
- Refactored config management in API routes to utilize the new setPath method for improved configuration updates.
2026-04-02 00:51:39 +07:00
psychomafia-tiger
f9f14749b5
docs: add community standards, GEO-optimized README, and issue templates (#175)
* docs: add community standards, GEO-optimized README, and issue templates

- Add CONTRIBUTING.md with updated plugin-based architecture guide
- Add CODE_OF_CONDUCT.md (Contributor Covenant v2.1)
- Add .github/PULL_REQUEST_TEMPLATE.md
- Add .github/ISSUE_TEMPLATE/ (bug report, feature request, docs, adapter request, config)
- Update README.md with GEO optimization: plain-text first line, Why OpenACP table, Use Cases, Known Limitations, FAQ, Security section, SEO image alt texts
- Add docs/images/banner.jpg

* docs: remove issue/PR templates — will be submitted in separate PR by contributor

* docs: address review feedback

- README: remove fragile external issue links from Why OpenACP table
- CONTRIBUTING: remove "keep files under 200 lines" rule (not in CLAUDE.md)
- CODE_OF_CONDUCT: replace public GitHub Issues with private email for enforcement (placeholder — owner to confirm)

---------

Co-authored-by: Tiger <mac@Macs-MacBook-Pro.local>
2026-03-31 15:54:53 +07:00
Amando
133867c84e
docs: add issue templates and PR template (#176)
* docs: add issue templates and PR template

* fix: address PR review feedback

- Fix version placeholder to YYYY.MDD.patch format
- Change config render from typescript to json
- Add routing note for Discord/Slack adapter issues
- Remove Web UI / Dashboard (not yet shipped)
- Replace hardcoded agent dropdown with freeform input
- Add backward compatibility and plugin template checklist to PR template
- Replace CONTRIBUTING.md ref with GitBook link

---------

Co-authored-by: Amando <amando@Amandos-Mac-mini.local>
2026-03-31 15:11:40 +07:00
317 changed files with 36747 additions and 3862 deletions

BIN
.DS_Store vendored

Binary file not shown.

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

View 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

View 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
View 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
View File

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

View File

@ -75,13 +75,13 @@ src/
All features are plugins. Core only provides infrastructure (ServiceRegistry, MiddlewareChain, EventBus, LifecycleManager). Plugins register services, commands, and middleware in their `setup()` hook.
- 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
View 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
View 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
View File

@ -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.
[![npm](https://img.shields.io/npm/v/@openacp/cli.svg)](https://www.npmjs.com/package/@openacp/cli)
[![Twitter Follow](https://img.shields.io/twitter/follow/openacp_ai?style=social)](https://x.com/openacp_ai)
[Documentation](https://openacp.gitbook.io/docs) · [Quick Start](#quick-start) · [Features](#features) · [Agents](#supported-agents) · [Contributing](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
[![Twitter Follow](https://img.shields.io/twitter/follow/openacp_ai?style=social)](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

View File

@ -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" }
```
---

View File

@ -79,7 +79,7 @@ hello-world/
The scaffold generates two documentation files to help you (and your tools) work with the plugin:
- **CLAUDE.md** — A comprehensive technical reference for AI coding agents. Contains the full plugin API, all 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

View File

@ -12,7 +12,7 @@ No state is lost. The agent process keeps running; only the "owner" of the sessi
A typical flow:
1. You are working at your desk with Claude Code 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.

View File

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

View File

@ -14,7 +14,7 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Solution:**
1. Open your Telegram group → **Edit → Administrators** → add your bot and enable at minimum "Manage Topics".
2. Confirm the chat ID in `~/.openacp/config.json` matches the group. The ID of a 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.
---

View File

@ -55,7 +55,7 @@ Create a new agent session. If you omit arguments, OpenACP walks you through an
/new claude ~/code/my-project # create directly
```
On Telegram, each session gets its own 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 951 KiB

BIN
docs/superpowers/.DS_Store vendored Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View 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

View 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)} &lt;workspace-path&gt;</code>`,
{ parse_mode: 'HTML' },
).catch(() => {})
}
})
}
```
- [ ] **Step 1b: Add `InlineKeyboard` to imports**
The top of `new-session.ts` has `import type { Bot, Context } from "grammy"` (line 1). Change it to:
```typescript
import type { Bot, Context } from "grammy";
import { InlineKeyboard } from "grammy";
```
Remove the `import { InlineKeyboard } from 'grammy'` line from inside the new code block added in Step 1a (it's a top-level import now).
- [ ] **Step 1c: Export `showAgentPicker` and `setupNewSessionCallbacks` from the file**
Both are already exported via `export async function` and `export function` in the code above. No additional change needed.
### Step 2: Register ns: callbacks in index.ts
- [ ] **Step 2a: Add imports in index.ts**
Add to the imports from `./new-session.js`:
```typescript
import { handleNew, handleNewChat, createSessionDirect, showAgentPicker, setupNewSessionCallbacks } from './new-session.js'
```
(Replace the existing import line for `new-session.js`.)
- [ ] **Step 2b: Register ns: callbacks in setupAllCallbacks**
Add after the `na:` handler (line 62) and before the `ar:` handler (line 65):
```typescript
// New Session button flow — must be before broad m: handler
setupNewSessionCallbacks(bot, core, chatId, getAssistantSession);
```
- [ ] **Step 2c: Update the `callback` case to handle ns:start**
Update the `callback` case (from Task 4) to also handle `ns:`:
```typescript
case 'callback': {
const cbData = item.action.callbackData
if (cbData === 's:settings') {
await handleSettings(ctx, core)
} else if (cbData === 'ns:start') {
await showAgentPicker(ctx, core, chatId)
}
break
}
```
### Step 3: Update core menu item
- [ ] **Step 3a: Change New Session action in core-items.ts**
In `src/core/menu/core-items.ts`, replace line 9:
```typescript
action: { type: 'delegate', prompt: 'User wants new session. Guide them through agent and workspace selection.' },
```
With:
```typescript
action: { type: 'callback', callbackData: 'ns:start' },
```
### Step 4: Build and commit
- [ ] **Step 4a: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 4b: Commit**
```bash
git add src/plugins/telegram/commands/new-session.ts \
src/plugins/telegram/commands/index.ts \
src/core/menu/core-items.ts
git commit -m "feat: button-driven New Session flow
New Session menu button now shows:
1. Agent picker (inline buttons, skip if only 1 agent)
2. Workspace picker (recent workspaces from session history)
3. 'Custom path...' delegates to AI for text input
4. Direct workspace selection creates session immediately
Uses workspace cache with numeric IDs to stay within
Telegram's 64-byte callback data limit."
```
---
## Task 7: Add re-export for telegram-overrides
**Files:**
- Modify: `src/plugins/telegram/commands/index.ts`
- [ ] **Step 1: Add re-export**
Add to the re-exports section at the bottom of `index.ts`:
```typescript
export { TELEGRAM_OVERRIDES } from './telegram-overrides.js'
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/openacp-workspace/OpenACP && pnpm build`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/plugins/telegram/commands/index.ts
git commit -m "chore: re-export TELEGRAM_OVERRIDES from commands index"
```
---
## Task 8: Manual Smoke Test
No automated tests for UI callback flows — these require grammY bot context which is hard to mock meaningfully. Verify manually.
- [ ] **Step 1: Build and start**
```bash
cd /Users/lucas/openacp-workspace/OpenACP && pnpm build
```
- [ ] **Step 2: Test each menu button in Telegram**
Open the Telegram group, type `/menu`, then test each button:
| Button | Expected behavior | Pass? |
|--------|-------------------|-------|
| 🆕 New Session | Shows agent picker buttons (or workspace picker if 1 agent) | |
| 📋 Sessions | Shows session list with status emoji + cleanup buttons + Refresh | |
| 📊 Status | Shows status text | |
| 🤖 Agents | Shows paginated agent list with install buttons | |
| ⚙️ Settings | Shows settings keyboard with toggle/select options | |
| 🔗 Integrate | Shows integration menu | |
| 🔄 Restart | Sends restart message, then restarts | |
| ⬆️ Update | Checks version, updates if available | |
| ❓ Help | Shows rich formatted help | |
| 🩺 Doctor | Runs diagnostics, shows report with fix buttons | |
- [ ] **Step 3: Test slash commands**
Type each command directly:
| Command | Expected | Pass? |
|---------|----------|-------|
| `/agents` | Paginated list with install buttons | |
| `/sessions` | Session list with cleanup + refresh | |
| `/doctor` | Diagnostic report with fix buttons | |
| `/help` | Rich formatted help | |
- [ ] **Step 4: Test New Session full flow**
1. `/menu` → tap "🆕 New Session" → agent picker appears
2. Tap an agent → workspace picker appears (recent workspaces + Custom)
3. Tap a recent workspace → session created with topic
4. Repeat: tap "Custom path..." → AI asks for workspace path
- [ ] **Step 5: Test Refresh button**
1. `/menu` → tap "📋 Sessions" → session list with Refresh button
2. Tap "Refresh" → list refreshes

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View 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"
```

File diff suppressed because it is too large Load Diff

View 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"
```

View 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"
```

File diff suppressed because it is too large Load Diff

View File

@ -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"
```

View 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)} &lt;workspace-path&gt;</code>`,
{ parse_mode: 'HTML' },
)
} catch { /* ignore */ }
}
})
```
Replace with:
```typescript
bot.callbackQuery(/^ns:custom:/, async (ctx) => {
const agentKey = ctx.callbackQuery.data.replace('ns:custom:', '')
try { await ctx.answerCallbackQuery() } catch { /* expired */ }
// Remove inline keyboard from wizard message so user can't click stale buttons
try {
await ctx.editMessageText(
`<b>🆕 New Session</b>\n` +
`Agent: <code>${escapeHtml(agentKey)}</code>\n\n` +
`⌨️ Waiting for workspace path...`,
{ parse_mode: 'HTML' },
)
} catch { /* ignore */ }
await _sendCustomPathPrompt(ctx, chatId, agentKey)
})
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds with no errors
- [ ] **Step 3: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 4: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts
git commit -m "feat: replace ns:custom AI delegation with force-reply path input"
```
---
### Task 4: Register force-reply interceptor in `setupNewSessionCallbacks`
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts`
The interceptor must be registered **inside `setupNewSessionCallbacks`** so it runs before the terminal `setupRoutes()` message handler in `adapter.ts`. It intercepts `message:text` events where the message is a reply to a known force-reply message, processes the path, and calls `next()` otherwise.
- [ ] **Step 1: Add `bot.on("message:text")` interceptor at the top of `setupNewSessionCallbacks`**
Insert as the **first** handler inside `setupNewSessionCallbacks` (before the `bot.callbackQuery('ns:start', ...)` line):
```typescript
// Intercept replies to force-reply messages (custom path input)
bot.on("message:text", async (ctx, next) => {
_pruneExpiredForceReplies()
const replyToId = ctx.message.reply_to_message?.message_id
if (replyToId === undefined) return next()
const entry = _forceReplyMap.get(replyToId)
if (!entry) return next()
_forceReplyMap.delete(replyToId)
await _handleCustomPathReply(ctx, core, chatId, entry)
})
```
- [ ] **Step 2: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds
- [ ] **Step 3: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 4: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts
git commit -m "feat: register force-reply interceptor for custom path wizard"
```
---
### Task 5: Remove `getAssistantSession` parameter dependency from `setupNewSessionCallbacks`
The `getAssistantSession` parameter in `setupNewSessionCallbacks` was only used by the `ns:custom:` callback body (now replaced). Clean it up to keep the signature lean.
**Files:**
- Modify: `src/plugins/telegram/commands/new-session.ts`
- Modify: `src/plugins/telegram/commands/index.ts` (call site)
- [ ] **Step 1: Check if `getAssistantSession` is used anywhere else in `setupNewSessionCallbacks`**
```bash
grep -n "getAssistantSession\|assistant\." /Users/lucas/code/openacp-workspace/OpenACP/src/plugins/telegram/commands/new-session.ts
```
Expected: the only usage was in the old `ns:custom:` body. If any other usages appear, skip this task.
- [ ] **Step 2: Remove `getAssistantSession` parameter from `setupNewSessionCallbacks` (only if Step 1 confirms no other usage)**
Change the function signature from:
```typescript
export function setupNewSessionCallbacks(
bot: Bot,
core: OpenACPCore,
chatId: number,
getAssistantSession?: () => { topicId: number; enqueuePrompt: (p: string) => Promise<string> } | undefined,
): void {
```
To:
```typescript
export function setupNewSessionCallbacks(
bot: Bot,
core: OpenACPCore,
chatId: number,
): void {
```
- [ ] **Step 3: Update the call site in `commands/index.ts`**
In `setupAllCallbacks`, change:
```typescript
setupNewSessionCallbacks(bot, core, chatId, getAssistantSession);
```
To:
```typescript
setupNewSessionCallbacks(bot, core, chatId);
```
- [ ] **Step 4: Update the import in `commands/index.ts` if `getAssistantSession` type is no longer needed there**
The `getAssistantSession` parameter in `setupAllCallbacks` itself is still used by other handlers (e.g., `setupSettingsCallbacks`), so leave the outer signature intact.
- [ ] **Step 5: Build to verify no type errors**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm build 2>&1 | tail -20
```
Expected: build succeeds
- [ ] **Step 6: Run all tests**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
pnpm test
```
Expected: all tests pass
- [ ] **Step 7: Commit**
```bash
cd /Users/lucas/code/openacp-workspace/OpenACP
git add src/plugins/telegram/commands/new-session.ts src/plugins/telegram/commands/index.ts
git commit -m "refactor: remove getAssistantSession param from setupNewSessionCallbacks"
```

View File

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

View 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

View File

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

View 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

View File

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

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

View File

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

View File

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

View 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

View 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

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

View File

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

View File

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

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

View 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") |

View File

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

View File

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

View File

@ -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",

View File

@ -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": {

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -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 {}

View File

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

View File

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

View File

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

View File

@ -304,17 +304,17 @@ describe('CLI command args parsing', () => {
describe('cmdInstall', () => {
it('parses package name from args[0]', () => {
const { args } = simulateDispatch(['install', '@openacp/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')
})
})
})

View File

@ -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)
})
})

View File

@ -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')
})
})

View File

@ -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",

View File

@ -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()

View File

@ -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')

View File

@ -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");

View File

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

View 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.");
});
});

View 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)
}
})
})

View 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')
})
})

View 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)
}
})
})

View 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')
})
})

View 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')
})
})

View 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')
})
})

View 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)
})
})

View 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)
})
})

View 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()
})
})

View 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
}

View 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')
})
})

View 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')
})
})

View 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()
})
})

View 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);
});
});

View 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()
})
})

View 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)
})
})

View 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'))
})
})

View File

@ -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);
}

View File

@ -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);

View File

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

View File

@ -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)
}
}

View File

@ -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 })
}

View File

@ -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" };

View File

@ -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
`)
}

View File

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

View File

@ -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.`)
}

View 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)}`)
}

View File

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

View File

@ -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 })

View File

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