Compare commits

..

496 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
Mr.Peter
f2472f2cb0
Merge pull request #188 from lngdao/fix/api-cors-sse
fix(api-server): CORS headers for SSE and PUT method
2026-04-02 00:54:04 +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
0xmrpeter
5121683a4e fix(new): add createThread flag to /new command with full args
/new <agent> <workspace> was creating a session without a topic.
Now passes createThread: true so it matches the behavior of all
other session creation paths.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:51:00 +07:00
0xmrpeter
1d5f397327 refactor(newchat): use event-driven control message instead of adapter method
Core emits session:threadReady event, Telegram adapter listens and
sends the control message. Removes sendInitialControlMessage from
the adapter interface — core only signals, adapters handle rendering.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:49:36 +07:00
0xmrpeter
10000d7ae0 feat(newchat): send control message with status + buttons in new topic
When /newchat creates a new thread, the adapter now sends the initial
control message (agent info, model, keyboard buttons) and pins it,
matching the old behavior before the refactor. Added
sendInitialControlMessage to the adapter interface.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:47:18 +07:00
0xmrpeter
2cd4f1c314 fix(newchat): create new thread/topic when running /newchat
The refactor lost the createThread flag — /newchat created a session
without a dedicated topic, so the response just showed an ID with
no way to navigate to it. Now passes createThread: true so the
adapter creates a new forum topic (Telegram) or thread (Discord/Slack).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:38:42 +07:00
0xmrpeter
d27e0b8835 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 00:31:52 +07:00
0xmrpeter
b794f6976e chore(package): update dev script to use dev-loop.sh for development environment
Replaced the existing TypeScript watch command in the dev script with a call to the new dev-loop.sh script for improved development workflow.
2026-04-02 00:31:45 +07:00
0xmrpeter
6e389ef2f8 feat(assistant): auto-detect dev vs production CLI command in prompt
In dev mode (running from dist/cli.js), the system prompt now tells
the assistant to use `node /path/to/dist/cli.js` instead of `openacp`,
since the global binary may not exist in dev environments.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:29:10 +07:00
0xmrpeter
80680a0d4f Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 00:21:00 +07:00
0xmrpeter
7571bd12ba enhance(api): add channel and thread information to session details
- Updated the API command output to include the channel ID and thread ID for better session tracking.
- Modified prompt constants to emphasize the necessity of passing `--channel <current_channel>` when creating sessions to avoid headless sessions.
- Enhanced session creation instructions to clarify the importance of specifying the channel to ensure user visibility in Telegram.
2026-04-02 00:20:52 +07:00
0xmrpeter
6c842041cf feat(assistant): inject current channel name into system prompt
Assistant now knows which platform (telegram, discord, slack) the
conversation is on, so it can adapt formatting and behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:17:22 +07:00
0xmrpeter
fe4757e768 fix(assistant): use markdown instead of HTML tags in system prompt
The streaming pipeline converts markdown → HTML via markdownToTelegramHtml,
which escapes raw HTML tags. Agent must use **bold** and `code` (markdown),
not <b>/<code> (HTML), for formatting to render correctly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:11:52 +07:00
0xmrpeter
738338e88d Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-02 00:04:41 +07:00
0xmrpeter
033f3cfe73 refactor(api-server): update permissions and logging for API server plugin
- Added 'events:emit' permission to the API server plugin.
- Changed default port to 21420 for the API server configuration.
- Replaced console logs with structured logging for better traceability.
- Updated tunnel plugin to start only after the API server has started, using the new 'api-server:started' event.
2026-04-02 00:04:34 +07:00
lngdao
0222a0e946 fix(api-server): add CORS headers for SSE and allow PUT method
- Add explicit methods list to fastify-cors config (including PUT, OPTIONS)
- Add CORS headers to SSE handler which bypasses Fastify middleware
  due to using raw http.ServerResponse directly
2026-04-02 00:00:54 +07:00
0xmrpeter
4463b486a9 improve(assistant): strengthen CLI instance dir instructions in system prompt
Make the system prompt explicitly explain what OpenACP is, what the
instance directory means, and why --dir is mandatory. Emphasize that
the path must never be changed, omitted, or guessed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 00:00:51 +07:00
0xmrpeter
c3e35e98b7 refactor(assistant): use --dir flag instead of cd for instance targeting
Replace cd-based approach with --dir flag which is more reliable —
AI agents can't forget to cd or get the path wrong when it's inline.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 23:59:52 +07:00
0xmrpeter
85e83cf5a1 Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-01 23:23:09 +07:00
0xmrpeter
9f9a8e6aab fix(tunnel): default tunnel enabled setting to true if not specified
Updated the tunnel plugin to default the 'enabled' setting to true when it is not explicitly defined in the configuration. This change ensures that settings created via copyInstance will not inadvertently disable the tunnel functionality.
2026-04-01 23:23:01 +07:00
0xmrpeter
bfde38adff fix(tunnel): add missing events:read permission
The tunnel plugin calls ctx.on('system:ready') but didn't declare
events:read permission, causing setup() to throw silently. The service
was never registered, so all tunnel startup logs were skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 23:22:35 +07:00
0xmrpeter
ad4a9f520c fix(assistant): use parent of .openacp dir as instance root path
ctx.root points to the .openacp/ directory itself, but the CLI
resolves instances by looking for .openacp/ in CWD. Use
path.dirname(ctx.root) so the assistant cds to the correct parent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 23:14:28 +07:00
0xmrpeter
880cd1d0fc feat(assistant): inject instance root path into system prompt
Assistant now always knows the instance root and is instructed to
cd to it before every openacp CLI command, preventing wrong-instance
or missing-context errors.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 23:02:53 +07:00
0xmrpeter
8cdfe4cd44 fix: disconnect existing bridge before creating new one
createBridge() was overwriting the bridge reference in the Map but not
disconnecting the old bridge. The old bridge's event listeners remained
active, causing agent events to be dispatched multiple times — resulting
in duplicated/garbled text in Telegram.

Now disconnects any existing bridge for the same session before creating
a new one.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:52:15 +07:00
0xmrpeter
bdfd40e1ad fix: make /restart and /update execute directly instead of delegating
These commands had simple logic before the refactor (restart immediately,
update + restart). Delegating to assistant for confirmation was unnecessary.
Changed both to command type in MenuRegistry and direct execution in handlers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:46:16 +07:00
0xmrpeter
b6a419aaab fix: handle delegated response type in adapter command dispatch
Add delegated check before silent in the command dispatch handler.
Without this, delegated responses would fall through to renderCommandResponse
and attempt to render an empty response.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:44:18 +07:00
0xmrpeter
c608b40531 fix: remove double bridge connection causing duplicated messages
AssistantManager.spawn() called connectSessionBridge() after createSession(),
but createSession() already creates and connects a bridge internally.
This caused two bridges to listen on the same session, duplicating every
agent event — resulting in repeated/garbled text in Telegram.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:41:09 +07:00
0xmrpeter
add905a40c docs: clean up and simplify gitbook documentation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:28:37 +07:00
0xmrpeter
e8af143c87 docs: update gitbook for recent specs (03-29 to 04-01)
Add new pages: output modes, workspaces (multi-instance), app connectivity.
Update 16 existing pages to reflect: tunnel auto-start/keepalive, JWT auth
system, SSE streaming, session config options, one-liner install, startup UX,
lazy session resume, new CLI commands (attach, remote), and new chat commands
(/mode, /model, /thought, /dangerous).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 21:24:26 +07:00
0xmrpeter
dfd95d8b31 add startup/restart debug logging and tunnel auth updates spec
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 20:42:26 +07:00
Mr.Peter
04f29de190
Merge pull request #186 from Open-ACP/refactor/cmd-assistant-impl
refactor: unify command dispatch, move assistant to core, extensible menu
2026-04-01 20:40:30 +07:00
Mr.Peter
ff5ccc7c1e
Merge pull request #187 from Open-ACP/feat/tunnel-auth-updates
feat: one-time code auth, tunnel merge + keepalive, copyable links
2026-04-01 20:39:39 +07:00
0xmrpeter
7d53337f7a docs: add spec and implementation plan for tunnel + auth updates
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 20:22:57 +07:00
0xmrpeter
4f6e1ac6f6 fix: address code review issues (test flaky, tunnel timing, code truncation)
- Fix test flaky: await store.flush() before destroy in both afterEach blocks
- Fix flush() to drain pending re-scheduled saves (loop until fully drained)
- Defer tunnel start to system:ready so API server port is available
- Truncate code values in GET /codes response (show first 8 chars only)
- Add comment explaining dual registerPlugin safety via Fastify encapsulation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 20:14:18 +07:00
0xmrpeter
055da3b800 feat(remote): use one-time codes, show copyable links outside box 2026-04-01 19:17:29 +07:00
0xmrpeter
303ce10aa9 chore: remove hono dependencies (viewer server merged into API server) 2026-04-01 19:17:24 +07:00
0xmrpeter
fc4b48b918 feat(tunnel): register viewer routes in API server, auto-start tunnel on boot
Wire viewer routes into ApiServerService instead of a standalone Hono server,
derive tunnel port from API server, and add deprecation warnings for tunnel.port
and tunnel.auth config fields.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 19:15:43 +07:00
0xmrpeter
d6231ad521 feat(display): show copyable links outside status checkmarks on startup
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 19:15:38 +07:00
0xmrpeter
8a10cab81f feat(tunnel): integrate keepalive ping into TunnelRegistry for system tunnel 2026-04-01 19:14:19 +07:00
0xmrpeter
fe1c6c430d refactor(tunnel): remove Hono server, accept apiPort in TunnelService.start()
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 19:12:59 +07:00
0xmrpeter
9488169fa1 feat(tunnel): add TunnelKeepAlive class for system tunnel liveness
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 19:10:22 +07:00
0xmrpeter
ac89dd1749 feat(tunnel): add Fastify viewer routes (port from Hono) 2026-04-01 19:10:10 +07:00
0xmrpeter
74de885336 feat(auth): add one-time code endpoints for remote access
Adds POST /api/v1/auth/codes (secret-only), GET /api/v1/auth/codes,
DELETE /api/v1/auth/codes/:code, and POST /api/v1/auth/exchange (no
auth — code in body is the credential) to enable secure remote token
issuance flows.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 19:07:13 +07:00
0xmrpeter
865c2d8ca4 feat(auth): add one-time code storage to TokenStore
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 19:01:44 +07:00
0xmrpeter
1b59e80977 fix: address code review critical and important issues
- Use closure core variable instead of args.coreAccess in command handlers
- Remove pendingResumes state machine from resume.ts
- Replace silent fallback with delegated in command-registry
- Fix plugin template signatures for registerMenuItem and registerAssistantSection
- Add delegated type to CommandResponse docs in plugin template
- Update test to match silent->delegated change

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 18:48:46 +07:00
0xmrpeter
24fbd3e670 docs: update plugin template for new registries, final cleanup
Add registerMenuItem/unregisterMenuItem and registerAssistantSection/unregisterAssistantSection
to PluginContext API docs in claude-md.ts and plugin-guide.ts templates.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 18:22:51 +07:00
0xmrpeter
288114bb61 refactor: simplify Telegram adapter, registry-based menu, remove assistant state and interactive flows
- Delete action-detect.ts and its tests (action detection removed)
- Remove interactive new-session flows (PendingNewSession, showAgentPicker, workspace/confirm steps)
- Remove handlePendingResumeInput from resume.ts
- Delete setupCommands() from commands/index.ts
- Remove assistant state (assistantSession, assistantInitializing) from adapter
- Replace spawnAssistant() with core.assistantManager.spawn()
- All topics (including assistant) now route through core.handleMessage()
- Replace hardcoded buildMenuKeyboard with MenuRegistry-based version
- Replace broad m: switch/case handler with generic MenuRegistry dispatch
- Clean up assistant.ts: remove spawnAssistant, buildAssistantSystemPrompt, handleAssistantMessage
- Remove action detection from DraftManager
- Update tests to match new behavior

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 18:21:01 +07:00
0xmrpeter
d1365f16e4 feat: replace silent command handlers with real implementations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 18:10:11 +07:00
0xmrpeter
dd83647b91 refactor: simplify SessionBridge with cleanup array and extracted methods
Replace 5 optional handler fields with a single cleanupFns array and listen() helper.
Inline wire*() methods into connect(). Extract dispatchAgentEvent(), resolvePermission(),
checkAutoApprove(), and emitAfterResolve() as clear helper methods.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 18:07:38 +07:00
0xmrpeter
4fbf164f2b feat: wire MenuRegistry, AssistantRegistry, AssistantManager into core
Integrates new registries into OpenACPCore constructor, registers them
as services, adds connectSessionBridge method, exposes plugin context
methods for menu/assistant extension, and exports from core index.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 18:05:03 +07:00
0xmrpeter
8441db7a91 feat: add delegated CommandResponse type for assistant delegation 2026-04-01 18:01:32 +07:00
0xmrpeter
83df3996c1 feat: add AssistantManager for core assistant lifecycle
Adds isAssistant field to Session, creates AssistantManager class with
spawn/respawn/get/isAssistant/waitReady methods, and exports from assistant index.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 18:00:52 +07:00
0xmrpeter
e057264434 feat: add AssistantRegistry with plugin-extensible system prompt and core sections
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:59:01 +07:00
0xmrpeter
806d255b76 feat: add default core menu items registration 2026-04-01 17:56:48 +07:00
0xmrpeter
6e13574155 feat: add MenuRegistry with plugin-extensible menu items
Adds MenuItem type to plugin/types.ts and a MenuRegistry class for managing
plugin-registered menu items with priority sorting and visibility filtering.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:55:51 +07:00
0xmrpeter
a809524f5a fix: address plan review issues
- Task 9: add full code for each command handler (/new, /cancel, /status, etc.)
- Task 10: fix broken build — remove adapter imports of deleted functions before committing
- Task 7: add connectSessionBridge() method to OpenACPCore
- Task 11: fix placeholder for assistantTopicId in menu callback handler

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 17:47:41 +07:00
0xmrpeter
bf6a4d9de3 plan: add command & assistant architecture refactor implementation plan
13-task plan covering MenuRegistry, AssistantRegistry, AssistantManager,
SessionBridge simplification, command handler migration, and Telegram
adapter cleanup. TDD approach with tests before implementation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 17:36:55 +07:00
0xmrpeter
86bd6e10bf chore: bump version to 2026.401.7
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:26:33 +07:00
0xmrpeter
26ca0caa08 Add command & assistant architecture refactor spec
Design doc for refactoring the three intertwined systems (command dispatch,
assistant session management, bot/chat flows) into clean, separated concerns
with plugin extensibility for assistant context and menu items.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 17:25:19 +07:00
0xmrpeter
dae1bfdebc feat: add testing entry and path mapping for TypeScript configuration
- Added a new entry for 'testing' in tsup.config.ts to include src/testing.ts.
- Updated tsconfig.json in the plugin-sdk package to include a path mapping for '@openacp/cli/testing' pointing to the generated testing type definition.
2026-04-01 17:25:11 +07:00
0xmrpeter
357f5ac5a1 chore: bump version to 2026.401.6
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:05:51 +07:00
0xmrpeter
a1472b28d5 fix: update fastify-type-provider-zod version and improve session error handling
- Changed fastify-type-provider-zod version from ^6.1.0 to ~5.1.0 in package.json and pnpm-lock.yaml for compatibility.
- Enhanced the fail method in the Session class to be idempotent, preventing multiple transitions to the error state.
- Updated tests to reflect the new behavior of the fail method, ensuring it does not throw on repeated calls.
2026-04-01 17:05:21 +07:00
0xmrpeter
4b6231c6ea chore: bump version to 2026.401.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 16:30:52 +07:00
0xmrpeter
c25734f6c6 Enhance URL and query handling in display spec and message formatter
Updated the buildTitle function in display-spec-builder.ts to handle "fetch" and "web" kinds, returning truncated URLs or queries if they exceed 60 characters. Modified message-formatter.ts to ensure URLs and queries are checked for "undefined" before processing, improving robustness in tool summary and title formatting.
2026-04-01 16:30:02 +07:00
0xmrpeter
fb9c410626 Enhance DebugTracer to handle circular references in log data
Updated the DebugTracer class to prevent circular reference issues when logging data. Introduced a WeakSet to track seen objects and replace circular references with a placeholder string "[Circular]" during JSON serialization. This change ensures that logging does not crash the application due to circular structures.
2026-04-01 16:22:34 +07:00
0xmrpeter
36895eacd0 Remove dead handleEnableDangerous/handleDisableDangerous functions
Clean up all remaining references to /enable_bypass and /disable_bypass:
- Remove handleEnableDangerous and handleDisableDangerous from admin.ts
- Update product-guide.ts to use /bypass_permissions
- Update help text in menu.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:21:44 +07:00
0xmrpeter
758dba53ba Rename /bypass to /bypass_permissions, remove legacy enable/disable commands
- Rename command from /bypass to /bypass_permissions for clarity
- Remove /enable_bypass and /disable_bypass bot commands (replaced by
  /bypass_permissions on|off which handles ACP + client-side fallback)
- Remove from STATIC_COMMANDS and bot.command() registration
- Update all references in admin.ts button callback and tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:20:06 +07:00
0xmrpeter
41f8912ee8 Register /mode, /model, /thought, /bypass in Telegram command menu
These commands already worked via the generic CommandRegistry
dispatcher but were missing from STATIC_COMMANDS, so they didn't
appear in Telegram's command autocomplete menu.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:15:06 +07:00
0xmrpeter
da313e2a1a Fix bypass detection: dont_ask and skip are deny modes, not bypass
"Don't Ask" denies unknown permissions (opposite of bypass which
auto-approves). Removed dontask, dont_ask, skip from BYPASS_KEYWORDS.

Remaining bypass keywords: bypass, dangerous, auto_accept

Updated tests in config-commands, session-bridge-autoapprove, and
control-message to reflect correct bypass semantics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:13:20 +07:00
0xmrpeter
b389b3b786 Add tests for control message updates and bypass sync
39 tests covering:
- isBypassActive: agent mode keywords, clientOverrides, both, neither
- buildSessionStatusText: unified bypass display, model/mode/thinking
- buildSessionControlKeyboard: button labels for bypass/TTS states
- Platform data merge: controlMsgId persists without overwriting
  topicId or skillMsgId (documents the overwrite bug that was fixed)
- session:configChanged event emission for /model, /mode, /bypass
- patchRecord merge safety: shallow merge pitfalls and correct pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:08:16 +07:00
0xmrpeter
93c06f6c62 Fix platform data overwrite in storeControlMsgId and duplicate patchRecord calls
storeControlMsgId had two bugs:
- Called itself recursively instead of this.controlMsgIds.set()
- patchRecord with { platform: { controlMsgId } } replaced entire
  platform object, wiping topicId and skillMsgId

Also removed duplicate patchRecord calls in new-session.ts and
resume.ts that ran after onControlMessage and overwrote controlMsgId.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:04:26 +07:00
0xmrpeter
4ef0e2a382 chore: bump version to 2026.401.4
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 15:56:43 +07:00
0xmrpeter
8ffbdd0644 refactor: adjust argument indexing in CLI commands for consistency
Updated argument indexing across multiple CLI command files to ensure the first argument is consistently used for the primary command. This change affects the `adopt`, `agents`, `api`, `config`, `install`, `integrate`, `tunnel`, and `uninstall` commands, improving usability and reducing confusion in command usage.

- Changed argument references from `args[1]` to `args[0]` for primary commands.
- Adjusted subsequent argument references accordingly to maintain correct functionality.
2026-04-01 15:56:03 +07:00
0xmrpeter
ff9c6028bb fix: dev-loop, config command, instance-context and startup improvements
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 15:48:43 +07:00
0xmrpeter
5b317264c1 Persist controlMsgId for control message updates across restarts
The in-memory controlMsgIds Map was lost on daemon restart, causing
updateControlMessage to silently fail for /model, /mode changes. Now
controlMsgId is persisted in the session record (same pattern as
skillMsgId) and hydrated from the record on first access.

- Add controlMsgId back to TelegramPlatformData (optional, for persist)
- Add storeControlMsgId helper: writes to Map + persists to record
- Add getControlMsgId helper: reads Map with fallback to session record
- updateControlMessage uses getControlMsgId for reliable message lookup

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 15:39:55 +07:00
0xmrpeter
881cbba08d Sync bypass button with ACP config and unify bypass display
The Enable Bypass button now delegates to the /bypass command (via
CommandRegistry) instead of directly mutating clientOverrides — so the
agent is informed via ACP setConfigOption when it supports a native
bypass mode, with client-side fallback when it doesn't.

Display is unified: both ACP-mode bypass and clientOverrides bypass now
show as "Mode: ☠️ Bypass Permissions enabled" (merged into the Mode
line) instead of a separate status line.

- Add isBypassActive(session) helper: checks agent mode + clientOverrides
- setupDangerousModeCallbacks: use registry.execute("/bypass on|off")
- buildSessionStatusText: merge bypass into Mode line
- setupTTSCallbacks + updateControlMessage: use isBypassActive

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 15:27:07 +07:00
0xmrpeter
2d583fd779 Fix control message updates when config changes via commands
Move Telegram-specific message ID storage from core to adapter, emit
session:configChanged events when /model, /mode, or /bypass commands
execute, and update both text and buttons inline when config changes.

- Remove controlMsgId/menuMsgId from TelegramPlatformData (core types)
- Store control message IDs in adapter Map<sessionId, msgId>
- Add session:configChanged event emission in config command handlers
- Update control message (text + buttons) when config changes
- Thread onControlMessage callback through new-session/resume commands
- Pass callback in all command and callback handler invocations

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-04-01 14:49:35 +07:00
0xmrpeter
d9d3fab470 fix: correct date format in version validation comment in install script 2026-04-01 13:58:03 +07:00
0xmrpeter
1909c179b6 chore: bump version to 2026.401.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 13:56:46 +07:00
0xmrpeter
998fbf806a chore: bump version to 2026.41.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 13:44:29 +07:00
0xmrpeter
5199709c43 feat: unify bypass UX messages across Telegram and Discord
Consistent phrasing: "Bypass enabled/disabled", shorter button labels,
clearer explanations. Matches core /bypass command style.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:37:43 +07:00
0xmrpeter
a733b1b257 feat: improve config command UX with friendlier messages
- Menu titles now show context: "Choose session mode (current: Code)"
- Success messages: "Mode switched to **Architect**."
- Better errors: "This agent does not support switching modes."
- Already-set check: "Already using **Code**." (no redundant agent call)
- Bypass status: descriptive sentences with emojis
- Already-in-state check: "Bypass is already enabled/disabled."
- Client-side bypass explains why with italic note

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:35:47 +07:00
0xmrpeter
448c8c11bc fix: update config command tests for improved UX messages
Update config-commands.test.ts to match renamed /bypass command (was /dangerous),
new menu titles, "switched to"/"Already using" messages, "Unknown option" errors,
already-in-desired-state checks, and direct configOptions assignment. Also fix
assistant-prompt.test.ts to expect "Bypass" instead of "Dangerous".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 13:35:18 +07:00
0xmrpeter
914fc013d6 refactor: rename 'dangerous mode' to 'bypass permissions' across documentation and code
- Updated all references from 'dangerous mode' to 'bypass permissions' in CLI commands, API documentation, and internal logic.
- Adjusted command usage and descriptions to reflect the new terminology for clarity and consistency.
- Removed warmup functionality from session management as part of the refactor.
2026-04-01 13:28:08 +07:00
0xmrpeter
e720f84dd0 fix(cli): correct plugin subcommand arg indexing and add local dir install docs
Args were off-by-one (args[2] instead of args[1]) after refactoring
the CLI dispatch. Also added help text for local directory install.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 13:09:32 +07:00
0xmrpeter
d1850da198 refactor: rename 'label' to 'name' in config options for consistency
- Updated the ConfigSelectChoice interface to replace 'label' with 'name'.
- Adjusted related code in API commands and tests to reflect this change.
- Ensured consistency across configuration options and improved clarity in the codebase.
2026-04-01 12:42:53 +07:00
0xmrpeter
8e9f371875 chore: bump version to 2026.41.2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 12:42:01 +07:00
0xmrpeter
de583cdfed fix: improve error logging and update permissions in API server and SSE adapter
- Added detailed error logging for plugin setup failures in the LifecycleManager.
- Updated API server and SSE adapter permissions to include 'services:use' for enhanced functionality.
- Enhanced logging during API server setup and system readiness events for better traceability.
2026-04-01 12:23:57 +07:00
0xmrpeter
55da9d5497 fix: enhance error handling and logging in API server and Telegram adapter
- Added error message handling in OpenACPCore to notify users of inactive sessions.
- Improved logging in the API server setup and startup process for better traceability.
- Updated Telegram adapter to use getOrResumeSession for session management, ensuring consistent session retrieval across commands.
- Enhanced retry logic in the API server to handle port conflicts more gracefully.
2026-04-01 12:07:36 +07:00
0xmrpeter
6f8b524076 fix: check shuttingDown in retry catch block to prevent post-shutdown retries
When a retry was already in-flight before shutdown set the flag, the
catch block would schedule another retry after shutdown killed the
process. Add shuttingDown guard in the catch path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:56:09 +07:00
0xmrpeter
cd18504f0d fix: spawn tunnel processes detached to prevent SIGINT propagation
When user presses Ctrl+C, SIGINT is sent to the entire process group.
cloudflared receives it directly, does graceful shutdown (reconnects to
edge), exits before our shutdown code runs, and triggers onExit retry.
Spawning with detached:true puts tunnels in their own process group so
only our code controls their lifecycle via stop().

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:52:16 +07:00
0xmrpeter
c44f11ac6c fix: update CLAUDE.md marker for local OpenACP workspace
Changed the marker in CLAUDE.md from '.openacp/' to '## Local OpenACP Workspace' to better reflect the current workspace terminology and improve clarity for users.
2026-04-01 11:06:14 +07:00
0xmrpeter
a9a8111ae1 Merge branch 'develop' of github.com-peter:Open-ACP/OpenACP into develop 2026-04-01 10:59:11 +07:00
0xmrpeter
3b689734da Merge branch 'develop' of github.com:Open-ACP/OpenACP into develop 2026-04-01 10:58:46 +07:00
0xmrpeter
e8aabd58fd chore: update workspace terminology and improve instance handling
Changes include:
- Updated `.gitignore` to include `.openacp` for local workspace secrets.
- Refactored CLI commands to replace "instance" with "workspace" for consistency.
- Enhanced workspace setup and registration logic, including deduplication of entries.
- Improved user prompts and error messages related to workspaces.
- Added functionality to protect local workspace secrets from being tracked by git.

This commit aims to clarify the distinction between workspaces and instances, enhancing user experience and code maintainability.
2026-04-01 10:58:33 +07:00
0xmrpeter
53edea1582 fix: address code review findings for config options migration
- Fix Telegram admin.ts store-only paths to use clientOverrides instead of dangerousMode
- Remove stale legacy fields from test mocks (currentMode, currentModel, etc.)
- Update EventBus type from dangerousMode to clientOverrides
- Deduplicate BYPASS_KEYWORDS and isPermissionBypass() into shared util
- Fix double middleware fire on /dangerous by using direct assignment
- Update stale comment in session-bridge.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:50:22 +07:00
0xmrpeter
b4d27a0af4 feat: add session config CLI commands
Add `openacp api session-config` subcommand group to manage ACP session
config options via the REST API: list options, set a value, show
clientOverrides, and toggle bypassPermissions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:41:03 +07:00
0xmrpeter
8e216c7933 feat: add session config API endpoints
Add REST API endpoints for managing session config options and client
overrides: GET/PUT /sessions/:id/config, GET/PUT /sessions/:id/config/overrides,
and PUT /sessions/:id/config/:configId for setting individual options via agent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:38:53 +07:00
0xmrpeter
4e4827de85 feat: add /mode, /model, /thought, /dangerous chat commands
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:35:52 +07:00
0xmrpeter
22e5b5639a fix: update integration, transformer, and history tests for config options migration
Remove tests for removed `current_mode_update` and `model_update` event types,
update mock sessions to use current Session fields (`configOptions`, `clientOverrides`),
and update history recorder test to use `config_option_update` event instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:27:49 +07:00
0xmrpeter
0b089b112f fix: update API server tests for clientOverrides migration
Replace flat `dangerousMode` property on mock sessions with
`clientOverrides.bypassPermissions` to match the current route
implementation, and update patchRecord expectations accordingly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:24:56 +07:00
0xmrpeter
7e9f319cc4 refactor: remove setMode/setModel and legacy middleware hooks
Remove the deprecated setMode() and setModel() methods from AgentInstance
since all config changes now go through setConfigOption(). Also remove the
mode:beforeChange and model:beforeChange middleware hooks from
MiddlewarePayloadMap and plugin templates, keeping config:beforeChange as
the single unified hook.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:22:32 +07:00
0xmrpeter
439d54b605 fix: update session-acp and session-lifecycle tests for config options migration
Replace removed fields (dangerousMode, currentMode, availableModes, currentModel,
availableModels, setInitialAcpState, updateMode, updateModel) with the new API:
setInitialConfigOptions, setAgentCapabilities, getConfigByCategory, getConfigValue,
updateConfigOptions, clientOverrides, and toAcpStateSnapshot.

Also fix source files that referenced removed Session.dangerousMode property and
removed AgentEvent types (current_mode_update, model_update) in agent-instance.ts,
message-transformer.ts, history-recorder.ts, and the api-server/telegram plugins.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:18:34 +07:00
0xmrpeter
a5eaff1fb6 refactor: update session-manager for clientOverrides
Replace dangerousMode: false with clientOverrides: {} in session record
creation and all test fixtures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:13:12 +07:00
0xmrpeter
87c85eb98f refactor: update session-factory for config options hydration and data migration
Replace setInitialAcpState() calls with setInitialConfigOptions() and
setAgentCapabilities(). Add backward-compatible migration: old records
with dangerousMode are converted to clientOverrides.bypassPermissions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:13:07 +07:00
0xmrpeter
7c2099291f refactor: update session-bridge for unified config options and bypass detection
Replace dangerousMode check with dual bypass detection: agent-side
(configOptions mode category with bypass keywords) and client-side
(clientOverrides.bypassPermissions). Remove current_mode_update and
model_update event handlers since those event types no longer exist.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:13:02 +07:00
0xmrpeter
83de4e91ec fix: force-kill tunnel processes during shutdown to prevent cloudflared reconnects
cloudflared ignores SIGTERM gracefully and tries to reconnect to edge
servers before exiting, causing network requests during shutdown. Add
force parameter to stop() that sends SIGKILL immediately, used by
shutdown() to skip graceful teardown.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:09:21 +07:00
0xmrpeter
4b213a0f12 refactor: migrate Session class to unified configOptions
Remove legacy fields (dangerousMode, currentMode, availableModes, currentModel,
availableModels) and methods (setInitialAcpState, updateMode, updateModel).
Add setInitialConfigOptions, setAgentCapabilities, getConfigOption,
getConfigByCategory, getConfigValue methods. Add clientOverrides field.
Update toAcpStateSnapshot to return only configOptions and agentCapabilities.

Note: Build errors in consumers are expected — other tasks fix them.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:05:37 +07:00
0xmrpeter
ab6780f0b6 refactor: update SessionRecord and AgentEvent types for config options migration
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:46:59 +07:00
0xmrpeter
3012a5568d docs: add session config options implementation plan
12-task plan covering types migration, session class, bridge, factory,
commands (/mode, /model, /thought, /dangerous), API routes, CLI, and tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:38:39 +07:00
0xmrpeter
8de3e1eff7 fix: enhance error handling in SendQueue and optimize MessageDraft HTML checks
- Updated SendQueue to suppress harmless "message is not modified" errors by resolving the item instead of rejecting it.
- Added logic in MessageDraft to skip sending if the rendered HTML is identical to the last sent content, improving efficiency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 09:34:26 +07:00
0xmrpeter
b8efcbca3f docs: add platform UI rendering section to config options spec
Added Section 6 covering Telegram/Discord/Slack button rendering,
command response format, and agent-initiated notification handling.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:24:24 +07:00
0xmrpeter
227a3e0295 docs: add session config options design spec
Unified ACP config options to replace separate mode/model/dangerous fields.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:19:19 +07:00
0xmrpeter
dcceb625d0 fix: review fixes + version bump to 2026.41.1
Review fixes:
- Clean up _pendingSkillCommands on session teardown (memory leak)
- Add .catch() to flushPendingSkillCommands (unhandled rejection)
- Extract Session.toAcpStateSnapshot() to DRY persistence logic
- Remove unnecessary `as any` casts on initialSessionResponse
- Add toAcpStateSnapshot mock to test fixtures

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 00:36:45 +07:00
0xmrpeter
3bdf34f38c feat: full ACP protocol gap closure — state propagation, timing fix, session commands
Major changes:
- Fix race condition: reorder createSession() to persist threadId BEFORE
  bridge.connect(), preventing skill commands and rename events from being
  silently dropped when agent fires events before threadId is available
- Extract and propagate ACP state (modes, configOptions, models, capabilities)
  from newSession/resumeSession response into Session via setInitialAcpState()
- Persist ACP state as cache in SessionRecord.acpState for display during
  lazy resume before agent reconnects (hybrid cache + override pattern)
- Add safety net: queue pending skill commands when threadId not yet set,
  flush when available; guard renameSessionThread against missing threadId
- Add session capability introspection via Session.supportsCapability()
- Add /fork, /close, /agentsessions system commands with capability checks
- Expose ACP state (currentMode, currentModel, capabilities) in API responses
- Update tests for new session properties

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 00:30:55 +07:00
0xmrpeter
71d56e0f42 fix: add flush() to TokenStore to resolve test race condition
scheduleSave() fires writeFile in background, but afterEach deletes
tmpDir before the write completes. flush() awaits pending saves,
called after destroy() in test cleanup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 00:29:04 +07:00
Mr.Peter
24ff365ca0
Merge pull request #179 from Open-ACP/refactor/core-phase1
refactor: core module Phase 1 — split core.ts + organize instance files
2026-04-01 00:09:30 +07:00
0xmrpeter
f0c79fe1e2 refactor: clean up core.ts after phase 1 extraction
Remove dead AgentEvent import — no longer referenced in core.ts after
prior phase 1 extraction tasks.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:04:58 +07:00
0xmrpeter
994a84e465 refactor: move handleNewSession, handleNewChat, createSessionWithContext to SessionFactory
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:03:03 +07:00
0xmrpeter
c32ed4824c refactor: move lazy resume from core.ts into SessionFactory
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:00:32 +07:00
0xmrpeter
a234320e5e refactor: extract AgentSwitchHandler from core.ts
Move agent switch orchestration logic (~200 lines) into a dedicated
AgentSwitchHandler class. core.ts now delegates via a thin wrapper,
keeping the public switchSessionAgent() API unchanged.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 23:56:34 +07:00
0xmrpeter
32caea5d59 refactor: group instance-* files into core/instance/
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 23:50:30 +07:00
0xmrpeter
283761838d fix: prevent tunnel retry during shutdown and optimize destroy flow
Null exitCallback in all providers' stop() to prevent unnecessary onExit
callbacks during intentional shutdown. Parallelize tunnel stops in
shutdown() and remove redundant spawnPromise await.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:47:26 +07:00
0xmrpeter
544a314f6c docs: fix blocking issues in Phase 1 plan (code review)
- B4: Remove createThread:false override from createFullSession callback
- B5: Add createThread to createFullSession type signature
- B6: Fix createSessionWithContext to pick fields, not spread params
- B2: Use optional chaining for middleware, preserve original semantics
- I2: Note handleNewChat as dead code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:45:25 +07:00
0xmrpeter
0c64218386 docs: add Phase 1 implementation plan for core refactor
5 tasks: group instance files, extract AgentSwitchHandler,
move lazy resume to SessionFactory, move convenience creation
methods, cleanup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:40:24 +07:00
0xmrpeter
2c335c0af9 docs: add instance directory grouping to core refactor spec
Phase 1d: Move 4 loose instance-* files into core/instance/ directory.
All belong to multi-instance management domain.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:36:57 +07:00
0xmrpeter
57f1db002a docs: fix 5 issues found in core refactor spec self-review
- Phase 1b: Move lazyResume to SessionFactory (not SessionManager) to avoid circular dep
- Phase 1c: Keep adoptSession in core.ts — it's orchestration, not factory logic
- Phase 2a: Detail event-driven TTS approach — middleware + EventBus listener pattern
- Phase 3b: Security fails closed (deny all) when securityGuard missing, not open
- Phase 3c: Tunnel cleanup via session:afterDestroy middleware, not wireSideEffects

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:33:45 +07:00
0xmrpeter
8beddd18b5 docs: add core module refactor design spec
3-phase incremental refactor plan for src/core/:
- Phase 1: Split core.ts (929→350 lines) — extract AgentSwitchHandler, move lazy resume to SessionManager, move session creation variants to SessionFactory
- Phase 2: Clean session.ts (569→400 lines) — extract TTS/voice into speech plugin middleware
- Phase 3: Decouple plugin services — remove tunnel awareness from MessageTransformer, graceful service degradation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:31:08 +07:00
Mr.Peter
ec956558ec
Merge pull request #178 from Open-ACP/fix/api-review-issues
fix: security hardening and edge case fixes for API server
2026-03-31 23:27:38 +07:00
0xmrpeter
8758421e0a fix: eliminate remaining hardcoded ~/.openacp paths for local instances
Thread instance-specific paths through remaining components:

- CloudflareTunnelProvider: binDir now passed from tunnel plugin via
  TunnelRegistry → TunnelService, so cloudflared binary is per-instance
- AgentCatalog: agentsDir now passed to installAgent, so agent binaries
  install to instance-specific agents/ directory
- Speech plugin: installNpmPlugin now receives pluginsDir from
  instanceRoot, so Edge TTS installs to the correct plugins/ dir

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:12:51 +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
408 changed files with 51553 additions and 6939 deletions

BIN
.DS_Store vendored

Binary file not shown.

@ -1 +0,0 @@
Subproject commit 90120c58fb32f31604b420f7c3899b80aed15213

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

7
.gitignore vendored
View File

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

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
@ -95,10 +95,10 @@ Published as `@openacp/cli` on npm. Users install with `npm install -g @openacp/
## Versioning
Format: `YYYY.MDD.<patch>` — e.g. `2026.327.1` is the first patch on March 27, 2026.
Format: `YYYY.MMDD.<patch>` — e.g. `2026.327.1` is the first patch on March 27, 2026.
- `YYYY` — year
- `MDD` — month + day (no leading zeros, since semver strips them). Jan 5 = `15`, Mar 27 = `327`, Dec 5 = `1205`
- `MMDD` — month (2-digit) + day (2-digit), leading zeros stripped by semver. Jan 5 = `105`, Mar 27 = `327`, Apr 1 = `401`, Dec 5 = `1205`
- `<patch>` — sequential patch number for that day, starting from 1
## Documentation Sync

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

BIN
docs/.DS_Store vendored

Binary file not shown.

View File

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

View File

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

View File

@ -4,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,14 +41,34 @@ openacp adopt <agent> <session_id> [--cwd <path>] [--channel <name>]
|---|---|
| `--cwd <path>` | Working directory for the session (default: current directory) |
| `--channel <name>` | Target channel adapter, e.g. `telegram`, `discord` (default: first registered) |
| `--json` | Output result as JSON |
**Examples**
```bash
openacp adopt claude abc123-def456
openacp adopt claude abc123 --cwd /path/to/project
openacp adopt claude abc123 --channel discord
openacp adopt claude abc123 --json
```
**JSON output** (`data` shape):
```json
{ "sessionId": "...", "threadId": "...", "agent": "claude", "status": "active" }
```
---
## attach
Connects to a running daemon and displays live status with log tailing. Useful for monitoring a daemon instance without opening a separate terminal.
**Usage**
```
openacp attach
```
Shows the daemon's current status (uptime, sessions, adapters, tunnel) and tails the log file. Press Ctrl+C to detach.
---
## agents
@ -45,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
@ -52,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
@ -69,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
@ -81,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
@ -119,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
@ -151,12 +228,12 @@ openacp api config
openacp api config set <key> <value>
```
### api dangerous
### api bypass
Enables or disables dangerous mode for a session. When enabled, the agent runs destructive commands without confirmation prompts.
Enables or disables bypass permissions for a session. When enabled, the agent runs destructive commands without confirmation prompts.
```
openacp api dangerous <session-id> on|off
openacp api bypass <session-id> on|off
```
### api delete-topic
@ -314,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 }
```
---
@ -330,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 }
}
```
---
@ -345,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.
@ -370,6 +472,7 @@ openacp integrate <agent> --uninstall
```bash
openacp integrate claude
openacp integrate claude --uninstall
openacp integrate opencode
```
---
@ -435,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.
@ -472,16 +585,59 @@ 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 }
```
---
## remote
Generates access links for connecting app clients to a running OpenACP instance. Displays local URL, tunnel URL (if enabled), app deep link, and a QR code.
**Usage**
```
openacp remote [--json]
```
| Flag | Description |
|---|---|
| `--json` | Output result as JSON (no QR code printed) |
The generated link includes a single-use access code valid for 30 minutes. The app exchanges this code for a JWT token on first use.
**Example output**
```
Local: http://127.0.0.1:21420
Tunnel: https://abc.trycloudflare.com
App: openacp://connect?host=abc.trycloudflare.com&code=xyz123
[QR code]
```
**JSON output** (`data` shape):
```json
{ "code": "xyz123", "name": "my-instance", "role": "owner", "expiresAt": "2026-04-02T13:00:00Z", "urls": { "local": "http://127.0.0.1:21420", "tunnel": "https://abc.trycloudflare.com", "app": "openacp://connect?host=abc.trycloudflare.com&code=xyz123" } }
```
See [App Connectivity](../features/app-connectivity.md) for the full guide.
---
## plugins
@ -490,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" }] }
```
---
@ -510,21 +675,56 @@ 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" }
```
---
## start
Starts OpenACP as a background daemon. Requires an existing config (run `openacp` first to set up).
Starts OpenACP. Requires an existing config (run `openacp` first to set up).
**Usage**
```
openacp start
openacp start [options]
```
**Options**
| Flag | Description |
|---|---|
| `--foreground` | Force foreground mode regardless of config |
| `--daemon` | Force daemon mode regardless of config |
| `--local` | Use local `.openacp/` instance in the current directory |
| `--global` | Use the global `~/.openacp/` instance |
| `--dir <path>` | Use a specific instance directory |
| `--name <id>` | Give the instance a name |
| `--from <source>` | Clone settings from an existing instance |
| `--json` | Output result as JSON |
**JSON output** (`data` shape):
```json
{ "pid": 12345, "instanceId": "global", "dir": "/Users/alice/.openacp" }
```
---
@ -535,7 +735,23 @@ Shows whether the OpenACP daemon is running and its PID.
**Usage**
```
openacp status
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 }
```
---
@ -546,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 }
```
---
@ -565,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
@ -578,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
@ -586,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
@ -594,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 }
```
---
@ -605,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 }
```
---
@ -632,16 +904,42 @@ Running `openacp` with no arguments starts the server. On first run, the setup w
- `foreground` — runs in the current terminal.
- `daemon` — spawns a background process and exits.
If a daemon is already running, `openacp` shows a rich status display with an interactive menu instead of an error:
- **r** — restart the daemon
- **f** — restart in foreground mode
- **s** — show full status
- **l** — tail logs
- **q** — quit
The startup display also shows which instance is active (global vs. local) and prints hints when a local instance is available but the global is being used.
`openacp --foreground` forces foreground mode regardless of config.
---
## --version / -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

@ -80,6 +80,14 @@ Map of named agent configurations. Each key is an agent name used in `defaultAge
---
## outputMode
| Field | Type | Default | Description |
|---|---|---|---|
| `outputMode` | `"low"` \| `"medium"` \| `"high"` | `"medium"` | Global default output mode. Overridden per adapter via `channels.<name>.outputMode` and per session via `/outputmode session`. See [Output Modes](../features/output-modes.md). |
---
## defaultAgent
| Field | Type | Default | Description |
@ -155,14 +163,11 @@ Map of named agent configurations. Each key is an agent name used in `defaultAge
| Field | Type | Default | Description |
|---|---|---|---|
| `tunnel.enabled` | boolean | `false` | Enable the built-in tunnel service |
| `tunnel.port` | number | `3100` | Default local port the tunnel service listens on |
| `tunnel.enabled` | boolean | `false` | Enable the built-in tunnel service. When `true`, the tunnel auto-starts on server boot with keepalive monitoring. |
| `tunnel.provider` | `"cloudflare"` \| `"ngrok"` \| `"bore"` \| `"tailscale"` | `"cloudflare"` | Tunnel provider |
| `tunnel.options` | object | `{}` | Provider-specific options (passed through to the tunnel process) |
| `tunnel.maxUserTunnels` | number | `5` | Maximum number of simultaneous user-created tunnels |
| `tunnel.storeTtlMinutes` | number | `60` | Minutes before expired tunnel entries are cleaned up |
| `tunnel.auth.enabled` | boolean | `false` | Require authentication to access tunnel endpoints |
| `tunnel.auth.token` | string | — | Auth token for tunnel access (when `tunnel.auth.enabled` is true) |
---

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,8 @@
# Getting Started: Your First Plugin
This tutorial walks you through creating, developing, testing, and publishing an OpenACP plugin from scratch. No prior knowledge of OpenACP internals is required.
This is a **hands-on tutorial** that walks you through creating, developing, testing, and publishing an OpenACP plugin from scratch. No prior knowledge of OpenACP internals is required.
> **Looking for the full API reference?** See [Writing Plugins — Full API Reference](../architecture/writing-plugins.md) for every API surface including services, middleware, events, settings, storage, and overrides.
---
@ -77,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

@ -1,6 +1,6 @@
# Plugin System
# Plugin System Overview
> **Note:** OpenACP has been refactored to a microkernel plugin architecture. This page provides a quick overview. For the full guide, see [Architecture > Plugin System](../architecture/plugin-system.md).
> **Note:** This page provides a quick overview of plugin management from a user's perspective. For the full technical deep dive into the plugin infrastructure, see [Architecture > Plugin System](../architecture/plugin-system.md).
---

View File

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

View File

@ -90,8 +90,8 @@ Configure via `~/.openacp/config.json` or the `/settings` command.
| Platform | Supported |
|---|---|
| Telegram | Yes |
| Discord | Coming soon |
| Slack | Coming soon |
| Discord | Yes |
| Slack | Yes |
---

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -192,7 +192,7 @@ Slash commands are registered automatically when OpenACP starts (guild-scoped, s
| `/install <name>` | Install an agent |
| `/outputmode [low\|medium\|high\|reset] [session]` | Set output detail level; use `session` scope to override for the current thread only |
| `/verbosity` | Deprecated alias for `/outputmode` |
| `/dangerous` | Toggle auto-approval of all permission requests |
| `/bypass` | Toggle auto-approval of all permission requests |
| `/tts [on\|off]` | Toggle text-to-speech for the current session |
| `/settings` | Change configuration in-chat |
| `/doctor` | Run system diagnostics |

View File

@ -143,7 +143,6 @@ Edit `~/.openacp/config.json` and add the Slack section (see the [full configura
"channels": {
"slack": {
"enabled": true,
"adapter": "slack",
"botToken": "xoxb-...",
"appToken": "xapp-1-...",
"signingSecret": "abcd1234efgh5678ijkl9012",
@ -158,7 +157,6 @@ Edit `~/.openacp/config.json` and add the Slack section (see the [full configura
| Field | Description |
|-------|-------------|
| `enabled` | Set to `true` to activate the Slack adapter |
| `adapter` | Must be `"slack"` |
| `botToken` | Bot User OAuth Token from Step 4 (starts with `xoxb-`) |
| `appToken` | App-Level Token from Step 2 (starts with `xapp-1-`) |
| `signingSecret` | Signing Secret from Step 7 |

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

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

View File

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

View File

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

View File

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

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.
---
@ -92,7 +109,7 @@ If you haven't finished initial setup, see the [Telegram Setup guide](../platfor
**Solution:**
1. Ensure the bot is running — buttons expire after the bot restarts if not answered.
2. If buttons appear but clicking does nothing, check logs for `Telegram bot error` entries that may indicate the bot token has been revoked.
3. Re-run setup (`openacp setup`) to regenerate configuration if the token is suspect.
3. Re-run setup (`openacp onboard`) to regenerate configuration if the token is suspect.
---

View File

@ -19,9 +19,9 @@ OpenACP responds to commands sent in your chat platform. This page covers every
| `/doctor` | Yes | Yes | Run system diagnostics |
| `/tunnel` | Yes | No | Create a public URL for a local port |
| `/tunnels` | Yes | No | List active tunnels |
| `/enable_dangerous` | Yes | No | Auto-approve all permissions |
| `/disable_dangerous` | Yes | No | Restore normal permission prompts |
| `/dangerous` | No | Yes | Toggle dangerous mode (Discord) |
| `/enable_bypass` | Yes | No | Auto-approve all permissions |
| `/disable_bypass` | Yes | No | Restore normal permission prompts |
| `/bypass` | No | Yes | Toggle bypass permissions (Discord) |
| `/text_to_speech` | Yes | No | Toggle TTS for a session |
| `/tts` | No | Yes | Toggle TTS (Discord) |
| `/outputmode` | Yes | Yes | Set output detail level (replaces `/verbosity`) |
@ -29,7 +29,11 @@ OpenACP responds to commands sent in your chat platform. This page covers every
| `/usage` | Yes | No | View token usage and cost |
| `/archive` | Yes | No | Archive a session topic |
| `/summary` | Yes | No | Generate an AI summary of a session |
| `/switch` | Yes | No | Switch to a different agent mid-conversation (Discord/Slack: coming soon) |
| `/mode` | Yes | Yes | Switch agent mode (code, architect, etc.) |
| `/model` | Yes | Yes | Switch agent model |
| `/thought` | Yes | Yes | Toggle thinking/reasoning mode |
| `/dangerous` | Yes | Yes | Toggle dangerous/bypass permissions mode |
| `/switch` | Yes | Yes | Switch to a different agent mid-conversation |
| `/handoff` | Yes | Yes | Continue session in your terminal |
| `/integrate` | Yes | Yes | Manage agent integrations |
| `/restart` | Yes | Yes | Restart OpenACP |
@ -51,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`
@ -128,9 +132,9 @@ Create a public HTTPS URL for a local port. Useful when an agent starts a dev se
List all active tunnels with their public URLs and stop buttons.
### `/enable_dangerous` / `/disable_dangerous` (Telegram) · `/dangerous` (Discord)
### `/enable_bypass` / `/disable_bypass` (Telegram) · `/bypass` (Discord)
Toggle dangerous mode for the current session. When enabled, all permission requests are auto-approved without showing buttons. Run inside a session topic. See [Permissions](permissions.md) for details.
Toggle bypass permissions for the current session. When enabled, all permission requests are auto-approved without showing buttons. Run inside a session topic. See [Permissions](permissions.md) for details.
### `/text_to_speech [on|off]` (Telegram) · `/tts [on|off]` (Discord)
@ -170,6 +174,47 @@ Archive the current session: stops the agent, marks the session as cancelled, an
Ask the agent to summarize what it has accomplished in the current session. Works inside a session topic.
### `/mode [mode-name]`
Switch the agent's operating mode. Without an argument, shows a menu of available modes declared by the agent (e.g., `code`, `architect`, `ask`).
```
/mode # show available modes
/mode code # switch to code mode
/mode architect # switch to architect mode
```
Available modes depend on the agent — they are declared via the ACP config options protocol.
### `/model [model-name]`
Switch the agent's model. Without an argument, shows available models.
```
/model # show available models
/model claude-sonnet # switch to a specific model
```
### `/thought [on|off]`
Toggle the agent's thinking/reasoning mode. When enabled, the agent shows its reasoning process.
```
/thought # toggle thinking mode
/thought on # enable thinking
/thought off # disable thinking
```
### `/dangerous [on|off]`
Toggle dangerous/bypass permissions mode for the current session. When enabled, the agent can perform destructive operations without confirmation prompts. This is equivalent to `/bypass` but routed through the agent's config options when available.
```
/dangerous # toggle dangerous mode
/dangerous on # enable (auto-approve all permissions)
/dangerous off # disable (restore normal prompts)
```
### `/switch [agent-name | label on|off]`
Switch to a different agent mid-conversation. The current conversation history is injected into the new agent so context is preserved.

View File

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

View File

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

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

View File

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

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -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.331.5",
"version": "2026.408.1",
"private": true,
"license": "MIT",
"type": "module",
@ -20,7 +20,7 @@
"scripts": {
"build": "tsc && mkdir -p dist/data && cp src/data/registry-snapshot.json dist/data/",
"build:publish": "tsx scripts/build-publish.ts",
"dev": "tsc --watch",
"dev": "./scripts/dev-loop.sh",
"dev:loop": "./scripts/dev-loop.sh",
"start": "node dist/cli.js",
"debug": "OPENACP_DEBUG=true pnpm start 2>&1 | pino-pretty",
@ -43,29 +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",
"@hono/node-server": "^1.19.11",
"@inquirer/prompts": "^8.3.2",
"diff": "^8.0.3",
"fastest-levenshtein": "^1.0.16",
"fastify": "^5.8.4",
"fastify-type-provider-zod": "^6.1.0",
"fastify-type-provider-zod": "~5.1.0",
"grammy": "^1.41.1",
"hono": "^4.12.8",
"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"
},
@ -75,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.331.5",
"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

View File

@ -8,7 +8,10 @@
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
"skipLibCheck": true,
"paths": {
"@openacp/cli/testing": ["../../dist/testing.d.ts"]
}
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/__tests__/**"]

796
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -31,6 +31,11 @@ while true; do
if [ "$EXIT_CODE" -eq "$RESTART_CODE" ]; then
echo ""
echo "▸ Restart requested (exit code $RESTART_CODE). Rebuilding..."
# Inherit instance root from previous run so we don't re-prompt
ROOT_FILE="${TMPDIR:-/tmp}/openacp-dev-loop-root"
if [ -f "$ROOT_FILE" ]; then
export OPENACP_INSTANCE_ROOT="$(cat "$ROOT_FILE")"
fi
build
echo "▸ Restarting..."
echo ""

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 ""
}
@ -554,7 +566,7 @@ validate_args() {
exit 1
fi
# Validate --version: allow 'latest', 'main', semver (YYYY.MDD.patch), or simple dist-tag
# Validate --version: allow 'latest', 'main', semver (YYYY.MMDD.patch), or simple dist-tag
if [[ "$INSTALL_TAG" != "latest" && "$INSTALL_TAG" != "main" ]]; then
if ! [[ "$INSTALL_TAG" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo "Error: --version contains invalid characters: $INSTALL_TAG" >&2
@ -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

@ -19,12 +19,8 @@ function createMockSession() {
status: 'active',
createdAt: new Date(),
promptCount: 0,
dangerousMode: false,
currentMode: undefined,
availableModes: [],
configOptions: [],
currentModel: undefined,
availableModels: [],
clientOverrides: {},
agentCapabilities: undefined,
permissionGate: { setPending: vi.fn() },
agentInstance: Object.assign(new TypedEmitter(), {
@ -36,9 +32,8 @@ function createMockSession() {
setName: vi.fn(),
finish: vi.fn(),
fail: vi.fn(),
updateMode: vi.fn(),
updateConfigOptions: vi.fn(),
updateModel: vi.fn(),
updateConfigOptions: vi.fn().mockResolvedValue(undefined),
toAcpStateSnapshot: vi.fn().mockReturnValue({}),
}) as unknown as Session
}
@ -72,17 +67,6 @@ describe('ACP Event Pipeline Integration', () => {
bridge.connect()
})
describe('mode switching flow', () => {
it('agent mode update → session state + adapter message', async () => {
session.emit('agent_event', { type: 'current_mode_update', modeId: 'architect' } as AgentEvent)
await vi.waitFor(() => {
expect(session.updateMode).toHaveBeenCalledWith('architect')
expect(adapter.sendMessage).toHaveBeenCalledWith('test-session',
expect.objectContaining({ type: 'mode_change', metadata: expect.objectContaining({ modeId: 'architect' }) }))
})
})
})
describe('config options flow', () => {
it('agent config update → session state + adapter message', async () => {
const options = [{ id: 'model', name: 'Model', type: 'select' as const, currentValue: 'sonnet', options: [] }]
@ -95,17 +79,6 @@ describe('ACP Event Pipeline Integration', () => {
})
})
describe('model update flow', () => {
it('agent model update → session state + adapter message', async () => {
session.emit('agent_event', { type: 'model_update', modelId: 'opus' } as AgentEvent)
await vi.waitFor(() => {
expect(session.updateModel).toHaveBeenCalledWith('opus')
expect(adapter.sendMessage).toHaveBeenCalledWith('test-session',
expect.objectContaining({ type: 'model_update' }))
})
})
})
describe('session info flow', () => {
it('agent session_info_update with title → setName + adapter message', async () => {
session.emit('agent_event', { type: 'session_info_update', title: 'New Title' } as AgentEvent)

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