Compare commits

...

221 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
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
Mr.Peter
6b4867854d
Merge pull request #196 from Open-ACP/develop
chore: merge develop into main
2026-04-03 10:29:30 +07:00
Mr.Peter
0fed71db58
Merge pull request #191 from Open-ACP/develop
Develop
2026-04-02 11:00:23 +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
224 changed files with 17594 additions and 2813 deletions

View File

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

104
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

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

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

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

View File

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

View File

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

59
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

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

2
.gitignore vendored
View File

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

View File

@ -75,13 +75,13 @@ src/
All features are plugins. Core only provides infrastructure (ServiceRegistry, MiddlewareChain, EventBus, LifecycleManager). Plugins register services, commands, and middleware in their `setup()` hook.
- 18 middleware hook points (message:incoming, agent:beforePrompt, permission:beforeRequest, etc.)
- 19 middleware hook points (message:incoming, agent:beforePrompt, permission:beforeRequest, etc.)
- 9 permission types (events:read, services:register, commands:register, etc.)
- Per-plugin settings via SettingsManager (~/.openacp/plugins/<name>/settings.json)
### Adapter Patterns
- **Forum topics** (Telegram): Each session gets its own topic
- **Topics** (Telegram): Each session gets its own topic
- **Callback routing**: Permission buttons use `p:` prefix, command buttons use `c/` prefix
- **Response renderers**: Adapters render CommandResponse types (text, menu, list, confirm, error, silent) per platform

53
CODE_OF_CONDUCT.md Normal file
View File

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

167
CONTRIBUTING.md Normal file
View File

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

101
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,15 +38,34 @@ 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>
@ -82,6 +105,13 @@ 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!
```
---
@ -150,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 |
@ -201,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">
@ -213,11 +296,7 @@ openacp tunnel list
## Contributing
We welcome contributions! See the [contributing guide](https://openacp.gitbook.io/docs/extending/contributing) for development setup, testing conventions, and PR process.
## Follow Us
[![Twitter Follow](https://img.shields.io/twitter/follow/openacp_ai?style=social)](https://x.com/openacp_ai)
We welcome contributions! See the [contributing guide](CONTRIBUTING.md) for development setup, testing conventions, and PR process. Have questions? Start a thread on [GitHub Discussions](https://github.com/Open-ACP/OpenACP/discussions).
## License

View File

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

View File

@ -79,7 +79,7 @@ hello-world/
The scaffold generates two documentation files to help you (and your tools) work with the plugin:
- **CLAUDE.md** — A comprehensive technical reference for AI coding agents. Contains the full plugin API, all 18 middleware hooks, permissions, testing utilities, and code patterns. An agent with zero prior context can read this file and write a complete plugin.
- **CLAUDE.md** — A comprehensive technical reference for AI coding agents. Contains the full plugin API, all 19 middleware hooks, permissions, testing utilities, and code patterns. An agent with zero prior context can read this file and write a complete plugin.
- **PLUGIN_GUIDE.md** — A shorter, practical guide for human developers. Covers the development workflow, code examples for common tasks (commands, services, middleware, settings), testing, and publishing.
### package.json

View File

@ -12,7 +12,7 @@ No state is lost. The agent process keeps running; only the "owner" of the sessi
A typical flow:
1. You are working at your desk with Claude Code open in the terminal.
1. You are working at your desk with Claude Code or OpenCode open in the terminal.
2. You need to step away but want to keep supervising the agent.
3. You run `openacp integrate` (or trigger the `/openacp:handoff` slash command from inside the agent).
4. The session appears as a new topic in your Telegram group or Discord server.
@ -30,7 +30,7 @@ Run the integrate command and follow the prompts:
openacp integrate
```
You will be asked which agent to integrate (Claude Code, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). The command installs the necessary hooks so your agent can hand off sessions to OpenACP.
You will be asked which agent to integrate (Claude Code, OpenCode, Cursor, Gemini CLI, GitHub Copilot, Cline, Codex, etc.). The command installs the needed integration so your agent can hand off sessions to OpenACP.
To uninstall later:
@ -56,19 +56,26 @@ The session appears as a new topic in your Telegram group or Discord server. You
- The OpenACP daemon must be running (`openacp start`) on the same machine as the terminal agent.
- At least one messaging adapter (Telegram, Discord, or Slack) must be configured and connected.
- `jq` must be installed on the machine (`brew install jq` on macOS, `apt install jq` on Linux).
- `jq` is required only for hook-based integrations (Claude/Cursor/Gemini/Cline). OpenCode plugin integration does not require `jq`.
---
## Supported agents
Currently supported agents include Claude Code, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, OpenAI Codex, and others. Run `openacp integrate --list` to see the full list.
Currently supported agents include Claude Code, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, OpenAI Codex, and others. Run `openacp integrate --list` to see the full list.
---
## Technical details
Handoff relies on two shell scripts installed by `openacp integrate`:
Most handoff integrations rely on two shell scripts installed by `openacp integrate`:
- **Inject hook** (`openacp-inject-session.sh`) — runs as an agent hook on every conversation turn, reads the agent's session ID from the hook payload, and injects it as a context variable.
- **Handoff script** (`openacp-handoff.sh`) — calls `openacp adopt <agent> <session_id>` to register the terminal session with the running OpenACP daemon, making it visible in the messaging platform.
For OpenCode, handoff is installed via a command + plugin pair under `~/.config/opencode/`:
- **Command** (`commands/openacp-handoff.md`) — provides `/openacp:handoff`.
- **Plugin** (`plugins/openacp-handoff.js`) — injects current OpenCode session ID so the command can call `openacp adopt opencode <session_id>`.
If OpenCode is started with `--pure`, plugins are disabled and session ID injection is unavailable. In this mode, `/openacp:handoff` is not supported.

View File

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

View File

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

View File

@ -55,7 +55,7 @@ Create a new agent session. If you omit arguments, OpenACP walks you through an
/new claude ~/code/my-project # create directly
```
On Telegram, each session gets its own forum topic. On Discord, a new thread is created in the configured channel.
On Telegram, each session gets its own topic. On Discord, a new thread is created in the configured channel.
### `/newchat`

BIN
docs/images/banner.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 951 KiB

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,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,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.403.2",
"version": "2026.408.1",
"private": true,
"license": "MIT",
"type": "module",
@ -61,6 +61,7 @@
"pino-pretty": "^13.1.3",
"pino-roll": "^4.0.0",
"qrcode-terminal": "^0.12.0",
"sanitize-html": "^2.17.2",
"zod": "^3.25.0",
"zod-to-json-schema": "^3.25.2"
},
@ -70,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.403.2",
"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

101
pnpm-lock.yaml generated
View File

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

View File

@ -30,6 +30,8 @@ $ERROR_C = "$ESC[38;2;239;68;68m" # red #ef4444
$MUTED = "$ESC[38;2;90;100;128m" # text-muted #5a6480
$NC = "$ESC[0m"
$INSTALLER_VERSION = "1.0.1"
$NODE_MIN_MAJOR = 20
function Write-Msg {
@ -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
}
@ -414,7 +433,8 @@ function Main {
if (-not $openacp) {
# Also check npm global prefix directly
try {
$npmPrefix = (& npm prefix -g 2>$null).Trim()
$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

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 ""
}
@ -686,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
@ -700,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
@ -729,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
}
@ -741,6 +786,52 @@ print_nvm_upgrade_hint() {
echo "Then open a new shell and rerun the installer."
}
# Ensure nvm init lines are present in all relevant shell config files.
# nvm's own installer only writes based on $SHELL, which may miss some configs.
# On macOS the primary shell is zsh — always patch ~/.zshrc regardless of other rc files.
patch_nvm_shell_configs() {
# shellcheck disable=SC2016
local nvm_init_lines
nvm_init_lines="$(cat <<'EOF'
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
EOF
)"
local marker='nvm.sh'
patch_rc() {
local rc="$1"
if ! grep -q "$marker" "$rc" 2>/dev/null; then
printf '\n# nvm (Node Version Manager)\n%s\n' "$nvm_init_lines" >> "$rc"
ui_info "Added nvm init to $rc"
fi
}
if [[ "$OS" == "macos" ]]; then
# macOS default shell is zsh. On a fresh machine ~/.zshrc may not exist yet —
# nvm installer only appends to existing files, so we must ensure ~/.zshrc exists.
touch "$HOME/.zshrc"
patch_rc "$HOME/.zshrc"
# Also patch bash configs if they exist
for rc in "$HOME/.bashrc" "$HOME/.bash_profile"; do
[[ -f "$rc" ]] && patch_rc "$rc"
done
else
# Linux: patch whichever rc files exist; create ~/.bashrc if none present
local patched_any=0
for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile"; do
if [[ -f "$rc" ]]; then
patch_rc "$rc"
patched_any=1
fi
done
if [[ "$patched_any" -eq 0 ]]; then
printf '# nvm (Node Version Manager)\n%s\n' "$nvm_init_lines" > "$HOME/.bashrc"
ui_info "Created ~/.bashrc with nvm init"
fi
fi
}
install_node() {
if [[ "$OS" == "macos" ]]; then
ensure_xcode_clt
@ -754,6 +845,7 @@ install_node() {
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
# shellcheck source=/dev/null
[[ -s "${NVM_DIR}/nvm.sh" ]] && source "${NVM_DIR}/nvm.sh"
patch_nvm_shell_configs
fi
if [[ -s "${NVM_DIR:-${HOME}/.nvm}/nvm.sh" ]]; then
@ -768,6 +860,10 @@ install_node() {
exit 1
fi
# Always ensure shell configs are patched (idempotent) — handles the case where
# nvm was already installed but ~/.zshrc didn't exist at that time.
patch_nvm_shell_configs
ui_success "Node.js v${NODE_DEFAULT_MAJOR} installed"
elif [[ "$OS" == "linux" ]]; then
@ -783,6 +879,7 @@ install_node() {
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
# shellcheck source=/dev/null
[[ -s "${NVM_DIR}/nvm.sh" ]] && source "${NVM_DIR}/nvm.sh"
patch_nvm_shell_configs
fi
if [[ -n "${NVM_DIR:-}" && -s "${NVM_DIR}/nvm.sh" ]] || [[ -s "${HOME}/.nvm/nvm.sh" ]]; then
@ -847,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
}
@ -942,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
@ -1220,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}"
@ -1258,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
@ -1278,6 +1402,10 @@ main() {
# ── Stage 2: Install ──
ui_stage "Installing OpenACP"
# Fix npm permissions before any npm global install, regardless of install method.
# Both "npm" and "git" paths may call `npm install -g` (pnpm, openacp).
fix_npm_permissions
if [[ "$INSTALL_METHOD" == "git" ]]; then
if ! check_git; then
install_git
@ -1289,8 +1417,6 @@ main() {
fi
install_openacp_from_git "$GIT_DIR"
else
fix_npm_permissions
local install_spec=""
install_spec="$(resolve_package_install_spec "$INSTALL_TAG")"
install_openacp_npm "$install_spec"
@ -1345,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..."
@ -1352,10 +1486,10 @@ main() {
exec </dev/tty
exec "$OPENACP_BIN"
else
ui_info "Run openacp to start the setup wizard"
ui_info "Then run: openacp"
fi
else
ui_info "Run openacp to get started"
ui_info "Then run: openacp"
fi
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -78,19 +78,6 @@ export function registerSessionCommands(registry: CommandRegistry, _core: unknow
},
})
registry.register({
name: 'clear',
description: 'Clear session history',
category: 'system',
handler: async (args) => {
if (!core.assistantManager) return { type: 'error', message: 'Assistant not available' }
const assistant = core.assistantManager.get(args.channelId)
if (!assistant) return { type: 'error', message: 'No assistant session for this channel.' }
await core.assistantManager.respawn(args.channelId, assistant.threadId)
return { type: 'text', text: '✅ Assistant history cleared.' }
},
})
registry.register({
name: 'newchat',
description: 'New chat, same agent & workspace',

View File

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

View File

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

View File

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

View File

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

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