Skip to content

Claude/custom system prompts 011 ay ygdk8 va px tnd va v5xrc#4711

Closed
telnet2 wants to merge 21 commits into
anomalyco:devfrom
telnet2:claude/custom-system-prompts-011AyYgdk8VaPXTndVaV5xrc
Closed

Claude/custom system prompts 011 ay ygdk8 va px tnd va v5xrc#4711
telnet2 wants to merge 21 commits into
anomalyco:devfrom
telnet2:claude/custom-system-prompts-011AyYgdk8VaPXTndVaV5xrc

Conversation

@telnet2

@telnet2 telnet2 commented Nov 24, 2025

Copy link
Copy Markdown

No description provided.

claude and others added 21 commits November 24, 2025 03:50
Add detailed documentation analyzing three key aspects of OpenCode:

1. MCP server connection support - covers entry points, configuration,
   connection lifecycle, protocol handling, tool registration, and
   error handling

2. Session multiple connections and message ordering - explains how
   multiple clients can connect to the same session and how message
   ordering is guaranteed through callback queues and locks

3. Multi-server statefulness - analyzes why OpenCode servers are
   stateful and require session affinity, documenting in-memory state
   that prevents horizontal scaling without distributed coordination
Add four additional documentation files analyzing OpenCode architecture:

1. event-historical-replay.md - Explains that OpenCode does NOT replay
   historical events on client connect; uses pull-based model for history
   and push-based for real-time updates

2. lsp-utilization.md - Comprehensive analysis of how OpenCode uses LSP
   including 19 built-in language servers, diagnostics injection, and
   symbol search capabilities

3. golang-project-prompts.md - Documents what prompts are sent for Go
   projects; importantly, there are NO Go-specific instructions - the
   model infers conventions from project structure and its training

4. lsp-selection-mechanism.md - Details how OpenCode selects which LSP
   server to use based on file extensions, root detection, and
   configuration hierarchy
Document the complete system prompt sent to LLMs including:

- All prompt template files (anthropic.txt, beast.txt, gemini.txt, etc.)
- Step-by-step construction process in resolveSystemPrompt()
- Full anthropic.txt content (106 lines) with all sections
- Environment context template with variable substitution
- Custom instructions loading from AGENTS.md/CLAUDE.md
- Final 2-message structure for caching optimization
- Complete example of final prompt for Claude on Go project
- Model-specific variations (GPT, Gemini, etc.)
…lity analysis

- Document all server-side APIs for session, message, and task management
- Document all client-side APIs including Bus events, Storage, and Provider
- Analyze event system for real-time subagent monitoring
- Provide implementation guide for new clients
- Assess feasibility of building clients in various languages (TypeScript, Python, Go, Rust)
- Include architecture patterns and feature parity matrix
- Document existing SDK (@opencode-ai/sdk) and web client (packages/desktop)
- Add packages overview showing all available client implementations
Add design document for enabling clients to register tool definitions
with the server and have the server delegate execution back to the client.

Key aspects covered:
- Protocol design with new message types for tool requests/responses
- Client tool registry for server-side management
- SDK client tools manager for registering and handling tools
- Both SSE and WebSocket communication options
- Security considerations (auth, sandboxing, rate limiting)
- Error handling and timeout management
- Usage examples for common scenarios
- Phased implementation plan
Comprehensive design documentation for deploying OpenCode as a
multi-tenant web service including:

- System architecture and component design
- Authentication, authorization, and multi-tenancy
- Database schema and storage strategies
- Horizontal scaling and Kubernetes deployment
- Security controls and compliance requirements
- API design with versioning and streaming support
Alternative storage design for MySQL deployments with:
- Snowflake-style BIGINT ID generation (8 bytes vs 16)
- No foreign keys, stored procedures, or triggers
- Application-level referential integrity
- Efficient cursor-based pagination
- Sharding strategy by organization
- Connection pooling and read/write splitting
Comprehensive analysis of OpenCode's todo and task tool systems including:
- TodoWrite and TodoRead tool definitions and data models
- Task tool for subagent spawning
- Internal storage design and event bus architecture
- Usage guidelines and prompts from todowrite.txt, todoread.txt, task.txt
- System integration points and UI rendering
- Data flow diagrams and common patterns
- File references with line numbers

This documentation provides a complete reference for understanding how
OpenCode implements task management and agent delegation.
Create a detailed 14-section whitepaper synthesizing all architectural
analysis into a cohesive document covering:

1. System Overview - Architecture style, technology stack, components
2. Core Architecture - Instance model, HTTP API, message flow
3. Session Management - Lifecycle, sequential processing, multi-client
4. MCP Server Integration - Configuration, lifecycle, tool registration
5. LSP Integration - 19 language servers, selection algorithm, usage
6. System Prompt Construction - Assembly pipeline, model-specific prompts
7. Event System - Bus architecture, event flow, client subscription
8. Storage Layer - File-based JSON storage, lock implementation
9. Concurrency Control - Multi-layer locking, race prevention
10. Multi-Server Considerations - Statefulness analysis, deployment options
11. Security Model - Permission system, MCP/LSP security
12. Performance Characteristics - Bottlenecks, optimizations, scalability
13. Design Decisions - Language-agnostic prompts, file storage, locking
14. Future Considerations - Enhancement opportunities, evolution phases

Includes comprehensive diagrams, decision rationales, trade-off analysis,
and complete reference appendices for files, events, and configuration.
Add detailed feature plan for implementing custom system and initial
prompt templates per session. This will enable users to create
specialized agents (e.g., data analyst, security auditor) by providing
custom prompt templates when starting a session.

Key features:
- Session-level custom prompt templates (persistent)
- Support for file-based and inline prompts
- Template resolution from project/global directories
- Auto-detection of file vs inline prompts
- Backward compatible with existing sessions
- Comprehensive implementation plan with ~145 LOC

The plan includes:
- Current architecture analysis
- Technical design and schema changes
- Implementation roadmap (3 phases)
- API changes and CLI integration
- Security considerations
- Testing strategy
- Example templates for data analyst and security auditor

Ready for review and implementation.
…2.0)

Expand the custom system prompt feature plan to include comprehensive
template variable interpolation in Phase 1 core implementation.

Major additions:
- 17 built-in variables (PROJECT_NAME, GIT_BRANCH, PRIMARY_LANGUAGE, etc.)
- Custom variables via session, config, or environment (OPENCODE_VAR_*)
- Variable syntax: ${VAR}, ${VAR:default}, ${VAR|filter}
- Filters: uppercase, lowercase, capitalize
- Auto-detection of primary programming language
- Git branch detection
- Variable resolution priority order

Implementation details:
- interpolateVariables() function with full variable map
- detectPrimaryLanguage() helper (extension-based detection)
- getGitBranch() helper for git integration
- extractEnvVariables() for OPENCODE_VAR_* support
- applyFilter() for variable transformations
- Updated Session schema to include variables field
- Task 1.5 added to Phase 1 implementation plan

Examples updated:
- Data analyst template with PROJECT_NAME, DATE variables
- Security auditor template with GIT_BRANCH, PLATFORM variables
- New team analyst example showing custom variables
- API examples showing variables field usage

Document changes:
- Updated executive summary with variable features
- Moved variable interpolation from Phase 4 to Phase 1
- Updated file modification summary (~250 LOC total)
- Version bump to 2.0 with changelog

Ready for implementation.
…lation

Implement core functionality for session-level custom prompt templates with
template variable interpolation support.

## Task 1.1: Extended Session Schema
- Added `customPrompt` field to Session.Info schema with type, value, loadedAt, and variables
- Updated Session.create schema to accept customPrompt parameter (string or object)
- Implemented parseCustomPromptInput() helper for auto-detecting file vs inline prompts
- Updated createNext() function to persist custom prompt metadata

## Task 1.2 & 1.5: Prompt Loading and Variable Interpolation
- Added fromSession() function to load and interpolate session-level prompts
- Implemented resolveTemplatePath() for file resolution (project, global, absolute paths)
- Added interpolateVariables() function for template variable substitution
- Implemented 17 built-in variables:
  * PROJECT_NAME, PROJECT_PATH, WORKING_DIR
  * GIT_BRANCH, GIT_REPO, PRIMARY_LANGUAGE
  * PLATFORM, DATE, TIME, DATETIME
  * USER, HOSTNAME, SESSION_ID, SESSION_TITLE
  * AGENT_NAME, MODEL_ID, OPENCODE_VERSION
- Added detectPrimaryLanguage() helper (extension-based detection)
- Added getGitBranch() helper for git integration
- Added extractEnvVariables() for OPENCODE_VAR_* support
- Added applyFilter() for variable transformations (uppercase, lowercase, capitalize)
- Variable syntax support: ${VAR}, ${VAR:default}, ${VAR|filter}
- File size limit: 100 KB for prompt templates

## Task 1.3: Updated Prompt Resolution
- Modified resolveSystemPrompt() to accept sessionID parameter
- Added call to SystemPrompt.fromSession() in priority order:
  1. Per-request system parameter
  2. Agent-specific prompt
  3. Session-level custom prompt (NEW)
  4. Model-specific default
  5. Environment context
  6. Custom instructions
- Updated all call sites to pass sessionID

## Task 1.4: API Validation and Config
- Session.create API now validates customPrompt field
- Added promptVariables field to Config.Info schema for global custom variables
- Security: path traversal prevention in resolveTemplatePath()

## Features
- File-based templates: load from .opencode/prompts/ or ~/.opencode/prompts/
- Inline templates: pass prompt text directly
- Auto-detection: automatically distinguish file paths from inline text
- Custom variables: session-specific, config-based, or environment (OPENCODE_VAR_*)
- Variable resolution priority: session > config > environment > built-in > default
- Backward compatible: sessions without custom prompts work as before

Files modified:
- src/session/index.ts (~50 LOC)
- src/session/system.ts (~180 LOC)
- src/session/prompt.ts (~10 LOC)
- src/config/config.ts (~5 LOC)

Total: ~245 LOC
Add CLI flags and template discovery commands for custom prompt templates.

## Task 2.1: Add CLI Flags
- Added --prompt <template> flag to run command (auto-detect file/inline)
- Added --prompt-file <path> flag for explicit file mode
- Added --prompt-inline <text> flag for explicit inline mode
- Updated session creation in run.ts to pass customPrompt parameter
- Implemented getCustomPrompt() helper to parse CLI args
- Updated both attach and bootstrap session creation paths

## Task 2.2: Template Discovery Command
- Created new `prompts` command with actions: list, show
- `opencode prompts list`: Lists all available templates
  * Shows project templates (.opencode/prompts/)
  * Shows global templates (~/.opencode/prompts/)
  * Displays template name and size in KB
  * Groups by location (project vs global)
- `opencode prompts show --name <template>`: Displays template details
  * Shows location, path, and size
  * Preview mode: first 10 lines (default)
  * Full mode: complete content (--verbose flag)
  * Helpful error message if template not found
- Registered PromptsCommand in main CLI

## Features
- Auto-detection of file vs inline prompts in run command
- Convenient template browsing and inspection
- Clear usage examples in command output
- Support for .txt and .md template files

## Usage Examples
```bash
# Use a template when running
opencode run --prompt data-analyst.txt "analyze this data"
opencode run --prompt-file ~/templates/security.txt "audit code"
opencode run --prompt-inline "You are a Python expert" "refactor this"

# List available templates
opencode prompts list

# Show template details
opencode prompts show --name data-analyst.txt
opencode prompts show --name security.txt --verbose
```

Files modified/added:
- src/cli/cmd/run.ts (~20 LOC modified)
- src/cli/cmd/prompts.ts (~200 LOC new)
- src/index.ts (~2 LOC modified)

Total: ~222 LOC
…mpts

This commit implements Phase 3 of the custom system prompts feature, focusing
on user experience improvements:

## Template Management (Task 3.1)
- Added create/edit/delete actions to prompts command
- Implemented createTemplate() with base template support
  - Supports --base flag to copy from existing templates (anthropic, beast, gemini, codex, qwen, polaris)
  - Auto-creates template directory if it doesn't exist
  - Opens template in $EDITOR after creation
  - Supports both project and global templates via --global flag
- Implemented editTemplate() to modify existing templates
  - Finds templates in project or global directories
  - Opens in configured $EDITOR
- Implemented deleteTemplate() with confirmation prompt
  - Interactive yes/no confirmation before deletion
  - Supports --global flag for explicit global template deletion

## Session Inspection (Task 3.2)
- Added custom prompt display in TUI session list
  - Shows 📄 emoji and file path for file-based prompts
  - Shows 📝 emoji for inline prompts
  - Displayed as subtitle in session list dialog
- Added custom prompt display in CLI run command
  - Shows "Custom prompt: file: <path>" or "Custom prompt: inline prompt"
  - Displayed after session creation in both attach and bootstrap modes
  - Uses info styling to make it visible but not intrusive

Changes:
- src/cli/cmd/prompts.ts: Added create/edit/delete functions (~200 LOC)
- src/cli/cmd/run.ts: Added custom prompt info display in both execution paths
- src/cli/cmd/tui/component/dialog-session-list.tsx: Added subtitle with custom prompt indicator

All three phases of the custom system prompts feature are now complete.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants