OpenACP/CLAUDE.md
dylan-112 1cb9b38388
feat: extract Discord plugin to standalone package
* fix(api): respect channel param in POST /api/sessions (#76)

Session creation always used the first registered adapter. Add optional
`channel` field so callers can target a specific platform (e.g. discord).
Falls back to first-adapter behavior when omitted for backward compat.

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

* fix(api): wire --channel flag in CLI and assistant prompts (#76)

The API endpoint accepted `channel` but the CLI `openacp api new` didn't
pass it through. Add --channel flag to CLI and update Discord/Telegram
assistant prompts to include --channel so sessions are created on the
correct platform.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 27c1f141d0c1

* docs: add session cleanup feature design spec

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 8de760ac911e

* docs: address spec review feedback for session cleanup

- Reference existing TopicManager and archiveSession() instead of reimplementing
- Add parseDuration utility for --older-than flag
- Fix API route collision (/api/cleanup/ instead of /api/sessions/cleanable)
- Add CleanupFlowState for Telegram selection state with TTL
- Clarify default filter excludes active/initializing
- Add archiving flag edge case to test plan

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 98610f1a27c8

* docs: add design spec for extracting Discord plugin to standalone package

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 10f437186acf

* docs: address spec review feedback for Discord plugin extraction

- Fix npm scope to @openacp (not @open-acp) for consistency
- Fix peerDependency version to match date-based versioning
- Move misclassified exports to "Need to add" section
- Add ConfigManager, AgentCatalog, requestRestart to SDK exports list
- Add essential: false, pluginDependencies notes
- Add tsconfig.json template
- Add exports field and .npmignore to package.json
- Add runAdapterConformanceTests to SDK testing exports
- Add legacy migration map update for backward compat
- Add boot order note for pluginDependencies

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: c5db89eae6aa

* docs: add implementation plan for extracting Discord plugin

9 tasks: extend CLI exports, extend SDK, migration map, scaffold
project, copy+refactor source, verify build, remove from OpenACP,
update README, push repos.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: a54a5510736a

* feat(core): export format-utils, message-formatter, CommandRegistry, Doctor, PRODUCT_GUIDE for plugin SDK

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 27b04551e9a7

* feat(plugin-sdk): export all symbols needed by adapter plugins

Entire-Checkpoint: a1ed33612eb6

* fix(plugin): add @openacp/plugin-discord migration alias for backward compat

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: a9db7beb2975

* fix(sdk): add missing adapter-primitive exports and testing entry point

- Add MessagingAdapterConfig, IRenderer, RenderedMessage type exports to src/core/index.ts
- Add DisplayVerbosity, ToolCallMeta, ToolUpdateMeta, ViewerLinks type exports
- Add STATUS_ICONS, KIND_ICONS, progressBar, formatTokens, truncateContent, stripCodeFences, splitMessage exports
- Add extractContentText, formatToolSummary, formatToolTitle, resolveToolIcon exports
- Create src/testing.ts as a separate entry point exporting runAdapterConformanceTests
- Add ./testing export map to @openacp/cli package.json
- Fix @openacp/plugin-sdk/testing.ts to import from @openacp/cli/testing
- Fix version strings to use valid semver (2026.326.4 not 2026.0326.4)

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

* fix: restore original version format YYYY.MMDD.patch

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

* feat: remove built-in Discord plugin (now available as @openacp/plugin-discord)

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

* fix(plugin): resolve 3 bugs preventing dev plugins from loading

- lifecycle-manager: include already-loaded plugins in dependency resolution
  so late-booted dev plugins aren't cascade-skipped
- dev-loader: use URL query string for ESM cache busting instead of copying
  to temp dir, which broke relative imports (e.g., './adapter.js')
- adapter-primitives: remove runAdapterConformanceTests from main barrel
  to prevent vitest from leaking into runtime bundle

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 64f604573bb7

* fix(review): address PR #80 code review feedback

- Remove core→plugin-discord import in config-editor (architecture violation):
  inline Discord token validation using REST API /users/@me instead of
  importing from @openacp/plugin-discord/validators
- Mark legacyMap in lifecycle-manager as @deprecated with migration notes
- Remove 98 planning artifacts from docs/superpowers/ (72k+ lines)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: cdeeaa98a4f1

* Revert "fix(plugin): resolve 3 bugs preventing dev plugins from loading"

This reverts commit 031464640560628dd8c093a4d8d30895c775ef98.

Entire-Checkpoint: 6ed1a02a0cb5

* Reapply "fix(plugin): resolve 3 bugs preventing dev plugins from loading"

This reverts commit 5707bf1c240f52baab277d21333cd7d92c191fac.

Entire-Checkpoint: bfaaa263a765

* revert: restore docs/superpowers/ plans and specs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 9195220e9172

* fix(review): revert unrelated changes and organize SDK sub-paths

- Revert --channel flag, assistant prompt changes, and session route
  changes that don't belong in Discord extraction PR (#82)
- Add SDK sub-path exports: @openacp/plugin-sdk/formatting,
  @openacp/plugin-sdk/config (alongside existing /testing) (#83)
- Mark SDK exports as @stable vs @experimental
- Fix plugin count test (10 → 9 after Discord removal)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 9bd5c44d98c4

* fix(review): address round 2 feedback on PR #80

- Rename @openacp/plugin-discord → @openacp/adapter-discord in all refs
  (setup-channels, wizard, lifecycle-manager, docs)
- Keep @openacp/plugin-discord as legacy alias in lifecycle-manager
- Remove unrelated session-cleanup-design.md spec from PR
- SDK: deduplicate main barrel by re-exporting from sub-path modules

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 4454289e400f

* fix(review): remove remaining Discord references from core

- Remove Discord doctor check from core (plugin registers its own)
- Dynamic adapter discovery via ServiceRegistry instead of hardcoded list
- Remove @openacp/discord from auto-register built-in plugins list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: c15c5fbf08c8

* fix(config): auto-install Discord plugin when enabling via config editor

When user enables or configures Discord through `openacp config` (not
onboarding), check if @openacp/adapter-discord is installed. If not,
prompt to install it automatically via npm.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: dd218c585ae3

* fix(review): round 3 cleanup — extensible ChannelId, update CLAUDE.md

- Change ChannelId from fixed union to string for extensibility
- Remove discord/ from CLAUDE.md project layout (now external plugin)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 66d8d185cda7

* fix(review): resolve all remaining Discord coupling in core

- Remove DiscordPlatformData from core types (plugin defines its own)
- Remove DiscordPlatformData from SDK re-exports
- Config editor: delegate Discord config to plugin configure() instead
  of 100+ lines of inline Discord logic
- Update integrate.ts help text to be adapter-agnostic
- Clean absolute local paths from planning docs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Entire-Checkpoint: 094cc484aaae

* fix: replace execSync npm install with async utility

Extract installNpmPlugin() into a shared utility that uses async exec
instead of execSync, preventing event loop blocking. Used by both
config-editor.ts and wizard.ts instead of inline execSync calls.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: 0xmrpeter <0xmrpeter@gmail.com>
2026-03-27 16:05:50 +07:00

9.8 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Build & Run

pnpm install            # Install dependencies
pnpm build              # TypeScript compile (tsc)
pnpm build:publish      # Bundle for npm publish (tsup → dist-publish/)
pnpm start              # Run: node dist/cli.js
pnpm dev                # Watch mode (tsc --watch)
pnpm test               # Run tests (vitest)

Architecture

OpenACP bridges AI coding agents to messaging platforms via the Agent Client Protocol (ACP). The flow:

User (Telegram) → ChannelAdapter → OpenACPCore → Session → AgentInstance (ACP subprocess)

Project Layout

src/
  cli.ts              — CLI entry (start, install, uninstall, plugins, --version, --help)
  main.ts             — Server startup, plugin boot
  index.ts            — Public API exports
  core/               — Core modules
    config/           — Zod-validated config, migrations, editor
    agents/           — Agent instance, catalog, installer, store
    sessions/         — Session, session-manager, session-bridge, permission-gate
    plugin/           — Plugin infrastructure (LifecycleManager, ServiceRegistry, MiddlewareChain, PluginContext)
    commands/         — System chat commands (session, agents, admin, help, menu)
    adapter-primitives/ — Shared adapter framework (MessagingAdapter, StreamAdapter, SendQueue, etc.)
    utils/            — Logger, typed-emitter, file utilities
    setup/            — First-run setup wizard
  plugins/            — All plugins (adapters + services)
    telegram/         — Telegram adapter (grammY)
    slack/            — Slack adapter (@slack/bolt)
    speech/           — TTS/STT (Edge TTS, Groq STT)
    tunnel/           — Port forwarding (Cloudflare, ngrok, Bore, Tailscale)
    security/         — Access control, rate limiting
    usage/            — Cost tracking, budget
    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 templates for `openacp plugin create`
  packages/
    plugin-sdk/       — @openacp/plugin-sdk (types + testing utilities)

Core Abstractions

OpenACPCore (core.ts) — Registers adapters, routes messages, creates sessions, wires agent events to adapters. Accesses services via ServiceRegistry.

Session (session.ts) — Wraps an AgentInstance with a prompt queue (serial processing), auto-naming, and lifecycle management.

AgentInstance (agent-instance.ts) — Spawns agent subprocess, implements full ACP Client interface. Converts ACP events to AgentEvent types.

LifecycleManager (plugin/lifecycle-manager.ts) — Boots plugins in dependency order (topo-sort), manages setup/teardown, handles version migration.

ServiceRegistry (plugin/service-registry.ts) — Central service discovery. Plugins register services, core accesses them via typed interfaces.

CommandRegistry (command-registry.ts) — Central command registry for chat commands. System and plugin commands registered here, adapters dispatch via generic handler.

PluginContext (plugin/plugin-context.ts) — Scoped API for plugins: events, services, middleware, commands, storage, logging.

Plugin System

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.)
  • 9 permission types (events:read, services:register, commands:register, etc.)
  • Per-plugin settings via SettingsManager (~/.openacp/plugins//settings.json)

Adapter Patterns

  • Forum topics (Telegram): Each session gets its own topic
  • Callback routing: Permission buttons use p: prefix, command buttons use c/ prefix
  • Response renderers: Adapters render CommandResponse types (text, menu, list, confirm, error, silent) per platform

npm Publishing

Published as @openacp/cli on npm. Users install with npm install -g @openacp/cli.

  • pnpm build:publish bundles CLI via tsup + builds SDK via tsc
  • GitHub Action auto-publishes both @openacp/cli and @openacp/plugin-sdk on tag push (v*)
  • Plugin system: openacp plugin install <name> installs from npm to ~/.openacp/plugins/

Versioning

Format: YYYY.MDD.<patch> — e.g. 2026.327.1 is the first patch on March 27, 2026.

  • YYYY — year
  • MDD — month + day (no leading zeros, since semver strips them). Jan 5 = 15, Mar 27 = 327, Dec 5 = 1205
  • <patch> — sequential patch number for that day, starting from 1

Documentation Sync

When changing code, you must update corresponding docs to keep code and documentation in sync:

  • New features: Must update README and docs/ (GitBook) to describe the feature, usage, and config if applicable.
  • Feature updates: Update related docs to reflect changes.
  • Bug fixes: Update docs if the bug relates to documented behavior. Not required if docs are still accurate.
  • General rule: Do not merge code without updating docs for new features or changes. README is for users, docs/ is for both users and contributors.
  • Plugin Template Sync: When changing plugin API, architecture, PluginContext, CommandDef, middleware hooks, permissions, or anything affecting how plugins are written → must update plugin template at src/cli/plugin-template/ (especially claude-md.ts and plugin-guide.ts) so templates always reflect the current API. These templates are the primary reference for both AI agents and plugin developers.

Conventions

  • English only: All code, comments, commit messages, documentation, specs, plans, and any text in the repository must be written in English. No exceptions.
  • ESM-only ("type": "module"), all imports use .js extension
  • TypeScript strict mode, target ES2022, NodeNext module resolution

Testing Conventions

General Principles

  • Test framework: Vitest. Test files live in src/**/__tests__/*.test.ts or src/**/*.test.ts.
  • Objective tests: Tests must be objective — verify behavior against specifications and expected outcomes, not against current implementation details. The source code is for understanding, but tests should validate what the code should do.
  • Test flows, not internals: Focus on testing user-facing flows and integration between components rather than individual private methods. Test the public API surface.
  • Edge cases matter: Always test boundary conditions, error paths, and state machine transitions. These are where bugs hide.

What to Test

  1. State machines: Test ALL valid transitions AND all invalid transitions. Verify events emitted on each transition.
  2. Flow tests: Test complete user flows end-to-end (e.g., message → session lookup → prompt → response → notification).
  3. Error recovery: Test that errors don't leave the system in a broken state. After an error, the system should be usable again.
  4. Concurrency: Test serial processing guarantees, queue ordering, lock behavior, and race conditions.
  5. Boundary values: Test exact boundaries (e.g., maxConcurrentSessions at exactly the limit, budget at exactly the threshold).
  6. Cleanup: Test that resources (timers, listeners, files) are cleaned up properly.
  7. Idempotency: Test double-calls (double connect, double disconnect, double resolve) are safe.

How to Write Tests

// Use vi.fn() for mocks, TypedEmitter for event-based mocks
function mockAgentInstance() {
  const emitter = new TypedEmitter<{ agent_event: (event: AgentEvent) => void }>();
  return Object.assign(emitter, {
    sessionId: "agent-sess-1",
    prompt: vi.fn().mockResolvedValue(undefined),
    cancel: vi.fn().mockResolvedValue(undefined),
    destroy: vi.fn().mockResolvedValue(undefined),
    onPermissionRequest: vi.fn(),
  }) as any;
}
  • Mock at boundaries: Mock AgentInstance, ChannelAdapter, SessionStore — not internal classes.
  • Use vi.waitFor() for async assertions on fire-and-forget operations.
  • Use vi.useFakeTimers() for timeout-based tests (e.g., PermissionGate timeout).
  • Cleanup in afterEach: Always destroy stores, clear timers, remove temp files.
  • No sleep/polling: Use await Promise.resolve() for microtask timing, vi.waitFor() for async ops.

Test Organization

  • src/core/__tests__/ — Core module tests (session, bridge, queue, permissions, store, etc.)
  • src/__tests__/ — Integration tests and adapter-level tests
  • src/plugins/*/ — Plugin-specific unit tests
  • Name files descriptively: session-lifecycle.test.ts, session-bridge-autoapprove.test.ts

Backward Compatibility

Users who installed and ran older versions will have config, data, and storage in the old format. When adding or changing anything related, you must ensure backward compatibility:

  • Config (~/.openacp/config.json): When adding new fields to Zod schema, always use .default() or .optional() so old configs don't fail validation. Never rename or remove fields without migration.
  • Storage / Data files (~/.openacp/): When changing data format (sessions, topics, state...), must handle old format — read old data and auto-migrate to new format if needed. Must not crash on data from previous versions.
  • CLI flags & commands: Do not remove or rename existing commands/flags. If deprecating, keep them working and log a warning.
  • Plugin API: When changing interfaces that plugins use, must maintain backward compat or bump major version.
  • General rule: New code must work with old data/config without requiring user action. If migration is needed, run it automatically on startup.