pi-openspec-context
v0.1.4
Published
Lightweight Pi extension for automatic OpenSpec context injection into system prompts
Maintainers
Readme
pi-openspec-context
A lightweight Pi extension that automatically injects OpenSpec context into system prompts at the start of each agent session.
Overview
pi-openspec-context enhances the Pi coding agent by seamlessly integrating OpenSpec specification data into the system prompt. This enables the AI agent to understand project structure, APIs, data models, and other specification-driven context without explicit user prompts.
Key Features
- Automatic Context Injection: Detects OpenSpec projects and injects context into
before_agent_starthook - Smart Caching: Caches extracted context per workspace to minimize CLI calls
- Flexible Detection: Works with both OpenSpec roots and registered OpenSpec stores
- Resilient Fallback: Gracefully handles missing
openspecCLI, timeouts, and errors - ANSI Sanitization: Strips color codes from context output for clean integration
- Type-Safe: Fully typed TypeScript implementation with strict mode enabled
Installation
As a Pi Package
You can install pi-openspec-context directly into Pi from either NPM or GitHub:
# Install from NPM
pi install pi-openspec-context
# Or install from GitHub
pi install github:raphaelbahat/pi-openspec-contextGlobal Installation (for local development)
npm install -g pi-openspec-contextThen add to your Pi configuration:
{
"extensions": [
"pi-openspec-context"
]
}Project-Local Installation
npm install --save-dev pi-openspec-contextPrerequisites
Required
- OpenSpec CLI: Must be installed and accessible in your PATH.
- Please follow the official OpenSpec Installation Documentation to set up the CLI.
- Verify with:
openspec --version
Optional
- Pi coding agent v0.84.0 or later (typically included with Pi installation)
Architecture & Behavior
Detection Strategy
The extension uses a two-tier detection approach:
- OpenSpec Root Detection: Traverses upward from the current working directory looking for
openspec/config.yaml - Store Detection: If no root is found, queries
openspec store list --jsonto match the current directory against registered stores
Context Extraction
Once a target is detected:
- Root Target: Executes
openspec contextat the root path - Store Target: Executes
openspec context --store <store-id>from the current directory
Caching
Extracted context is cached in-memory per target:
- Root targets are keyed by absolute path
- Store targets are keyed by store ID
- Cache persists for the lifetime of the Pi session
Injection
The cleaned context is injected into the system prompt using a marker:
[OpenSpec context]
<extracted context data>Configuration
The extension works with zero configuration. Simply install and enable it.
Environment Variables
Optional environment variable to override the default timeout:
OPENSPEC_CONTEXT_TIMEOUT_MS: Timeout foropenspecCLI execution (default: 10000ms)
Troubleshooting
"openspec: command not found"
Problem: The extension runs but no context is injected.
Solution:
- Verify OpenSpec is installed:
which openspec - If missing, follow the OpenSpec Installation Documentation.
- Check PATH is configured:
echo $PATH - Restart Pi after installing OpenSpec
Context Not Appearing in Prompts
Problem: Extension is loaded but context not injected.
Checklist:
- Confirm you're in an OpenSpec root or registered store:
openspec store list - Verify OpenSpec can extract context:
openspec context - Check extension is loaded: Look for "pi-openspec-context" in Pi logs
- Inspect cache behavior: Add debug logging to extension
Timeout Errors
Problem: Extension times out and falls back silently.
Solution:
- Test OpenSpec manually:
time openspec context - Increase timeout if needed: Set
OPENSPEC_CONTEXT_TIMEOUT_MS=30000 - Check for hung
openspecprocesses:ps aux | grep openspec
Empty or Whitespace-Only Context
Problem: OpenSpec runs but returns empty output.
Solution:
- Verify OpenSpec project is valid:
openspec validate - Check for malformed YAML in
openspec/directory - Try manual context extraction:
openspec context
API Reference
Extension Export
The package exports a default extension factory:
import extension from 'pi-openspec-context';
// Used automatically by Pi's extension loader
extension(pi);Custom Cache Usage
For advanced use cases, you can create an extension with a custom cache:
import { createExtension, contextCache } from 'pi-openspec-context';
// Use default shared cache
const ext = createExtension();
ext(pi);
// Or provide custom cache
import { OpenSpecContextCache } from 'pi-openspec-context/cache';
const customCache = new OpenSpecContextCache();
const extWithCustomCache = createExtension(customCache);
extWithCustomCache(pi);Cache Methods
get(target): string | null- Retrieve cached contextset(target, context): void- Store context in cachehas(target): boolean- Check if target is cacheddelete(target): boolean- Remove specific target from cacheclear(): void- Clear all cached contextssize(): number- Get cache entry count
Development
Building
npm run buildTesting
npm run test # Run all tests
npm run test:watch # Watch mode
npm run test:e2e # Docker E2E tests onlyType Checking
npm run typecheckLinting
npm run lintArchitecture Notes
Modules
src/types.ts: Core type definitions (discriminated unions, interfaces)src/runner.ts: OpenSpec CLI execution and ANSI sanitizationsrc/detector.ts: Root and store detection logicsrc/cache.ts: In-memory caching with path normalizationsrc/index.ts: Pi extension lifecycle hook implementation
SOLID Principles
- Single Responsibility: Each module has one clear purpose
- Open/Closed: Extension logic is frozen but cacheable via factory function
- Liskov Substitution: Cache implements a standard interface
- Interface Segregation: Types are minimal and focused
- Dependency Inversion: Depends on
PiExecContextinterface, not concrete implementations
Error Handling
All errors are caught and logged silently. The extension falls back gracefully:
- Missing
openspecCLI → returns{} - CLI errors → returns
{} - Timeout → returns
{} - Empty output → returns
{}
This ensures the extension never breaks the agent workflow.
License
MIT License
Attribution
Based on original work by tobias-weiss-ai-xr/pi-openspec
Created by Raphael Bahat
