Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Makefile.skills
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.PHONY: skill-validate-all skill-convert-codocs skill-install-deps

skill-validate-all:
@echo "Validating all skills..."
@for f in $$(find skills -name "SKILL.md"); do \
go run cmd/sin/main.go skill validate $$f || true; \
done

skill-convert-codocs:
@echo "Converting CoDocs to skills..."
@echo "TODO: Implement conversion"

skill-install-deps:
@echo "Skill infrastructure ready"
27 changes: 27 additions & 0 deletions chains/sin-full-lifecycle.chain.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "sin-full-lifecycle",
"description": "Complete software delivery pipeline using SIN skills",
"steps": [
{
"skillName": "spec",
"on_failure": "abort",
"max_retries": 1,
"variables": {}
},
{
"skillName": "plan",
"on_failure": "abort",
"max_retries": 1,
"variables": {}
},
{
"skillName": "build",
"on_failure": "retry",
"max_retries": 3,
"variables": {}
}
],
"on_success": "stop",
"on_failure": "abort",
"max_loops": 1
}
159 changes: 159 additions & 0 deletions cmd/sin-code/headroom_cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// cmd/sin-code/headroom_cmd.go
package main

import (
"context"
"fmt"
"io"
"os"
"time"

"github.com/OpenSIN-Code/SIN-Code/internal/headroom"
"github.com/spf13/cobra"
)

// headroomCmd represents the headroom command
var headroomCmd = &cobra.Command{
Use: "headroom",
Short: "Manage Headroom context compression integration",
Long: `Headroom provides intelligent context compression for LLM requests.
It can reduce token usage by up to 92% with minimal accuracy loss.

Subcommands:
enable Enable Headroom compression
disable Disable Headroom compression
stats Show compression statistics
learn Manually trigger learning from a session log
test Test Headroom connection and compression
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()

Check warning

Code scanning / gosec

Errors unhandled Warning

Errors unhandled
},
}

var headroomEnableCmd = &cobra.Command{
Use: "enable",
Short: "Enable Headroom compression",
RunE: func(cmd *cobra.Command, args []string) error {
cfg := headroom.LoadConfigFromEnv()
cfg.Enabled = true
fmt.Println("✅ Headroom compression enabled")
fmt.Println(" Mode:", cfg.Mode)
fmt.Println(" Level:", cfg.CompressionLevel)
return nil
},
}

var headroomDisableCmd = &cobra.Command{
Use: "disable",
Short: "Disable Headroom compression",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("❌ Headroom compression disabled")
return nil
},
}

var headroomStatsCmd = &cobra.Command{
Use: "stats",
Short: "Show compression statistics",
RunE: func(cmd *cobra.Command, args []string) error {
cfg := headroom.LoadConfigFromEnv()
comp := headroom.NewCompressor(cfg)
ctx := context.Background()
if err := comp.Start(ctx); err != nil {
return fmt.Errorf("headroom not available: %w", err)
}
defer comp.Close()

stats := comp.GetStats()
fmt.Printf("📊 Headroom Statistics\n")
fmt.Printf(" Total requests: %d\n", stats.TotalRequests)
fmt.Printf(" Total compressed: %d\n", stats.TotalCompressed)
fmt.Printf(" Original tokens: %d\n", stats.TotalOriginalTokens)
fmt.Printf(" Compressed tokens: %d\n", stats.TotalCompressedTokens)
fmt.Printf(" Average savings: %.2f%%\n", stats.AverageSavings)
if !stats.LastLearnTime.IsZero() {
fmt.Printf(" Last learning: %s\n", stats.LastLearnTime.Format(time.RFC3339))
}
return nil
},
}

var headroomTestCmd = &cobra.Command{
Use: "test",
Short: "Test Headroom connection and compression",
RunE: func(cmd *cobra.Command, args []string) error {
cfg := headroom.LoadConfigFromEnv()
comp := headroom.NewCompressor(cfg)
ctx := context.Background()
if err := comp.Start(ctx); err != nil {
return fmt.Errorf("headroom not available: %w\nInstall headroom: pip install headroom-ai[all]", err)
}
defer comp.Close()

testContent := `This is a test of headroom compression. It should reduce the token count significantly.
Repeat this sentence many times to see the effect. Repeat this sentence many times to see the effect.
Repeat this sentence many times to see the effect.`

compressed, result, err := comp.CompressContent(ctx, testContent)
if err != nil {
return fmt.Errorf("compression test failed: %w", err)
}

fmt.Println("🔍 Headroom Test Result:")
fmt.Printf(" Original length: %d chars (~%d tokens)\n", len(testContent), len(testContent)/4)
fmt.Printf(" Compressed length: %d chars (~%d tokens)\n", len(compressed), len(compressed)/4)
if result != nil {
fmt.Printf(" Savings: %.2f%%\n", result.SavingsPercent)
fmt.Printf(" Algorithm: %s\n", result.Algorithm)
fmt.Printf(" Duration: %d ms\n", result.DurationMs)
}
fmt.Println("\n✅ Headroom is working correctly!")
return nil
},
}

var headroomLearnCmd = &cobra.Command{
Use: "learn [file]",
Short: "Learn from a failed session log",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var logContent string
if len(args) > 0 && args[0] != "" {
data, err := os.ReadFile(args[0])
if err != nil {
return fmt.Errorf("failed to read log file: %w", err)
}
logContent = string(data)
} else {
// Read from stdin
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
logContent = string(data)
} else {
return fmt.Errorf("please provide a session log file or pipe to stdin")
}
}

cfg := headroom.LoadConfigFromEnv()
client := headroom.NewCLIClient(cfg)
if err := client.Learn(context.Background(), logContent); err != nil {
return fmt.Errorf("learning failed: %w", err)
}
fmt.Println("✅ Headroom learned from the provided session")
return nil
},
}

func init() {
rootCmd.AddCommand(headroomCmd)
headroomCmd.AddCommand(headroomEnableCmd)
headroomCmd.AddCommand(headroomDisableCmd)
headroomCmd.AddCommand(headroomStatsCmd)
headroomCmd.AddCommand(headroomTestCmd)
headroomCmd.AddCommand(headroomLearnCmd)
}
125 changes: 125 additions & 0 deletions cmd/sin-code/headroom_extra_cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// cmd/sin-code/headroom_extra_cmd.go
package main

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"

"github.com/OpenSIN-Code/SIN-Code/internal/headroom"
"github.com/spf13/cobra"
)

var (
proxyAddr string
proxyUpstream string
lessonsPath string
)

// headroomProxyCmd starts the Headroom HTTP compression proxy.
var headroomProxyCmd = &cobra.Command{
Use: "proxy",
Short: "Run the Headroom HTTP compression proxy",
Long: `Starts a reverse proxy that intercepts OpenAI-compatible chat requests,
compresses message contents through Headroom, and forwards them upstream.

Point your LLM client's base URL at this proxy for zero-code-change compression:

sin-code headroom proxy --addr :8787 --upstream https://api.openai.com
export OPENAI_BASE_URL=http://localhost:8787/v1
`,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := headroom.LoadConfigFromEnv()
cfg.Enabled = true
// The proxy needs a backend that actually compresses; prefer CLI mode
// so the proxy itself does the work rather than delegating to a proxy.
if cfg.Mode == headroom.ModeProxy {
cfg.Mode = headroom.ModeCLI
}

comp := headroom.NewCompressor(cfg)
ctx := context.Background()
if err := comp.Start(ctx); err != nil {
return fmt.Errorf("headroom backend not available: %w\nInstall headroom: pip install headroom-ai[all]", err)
}
defer comp.Close()

proxy, err := headroom.NewProxy(cfg, comp, proxyUpstream)
if err != nil {
return err
}

// Graceful shutdown on SIGINT/SIGTERM.
errCh := make(chan error, 1)
go func() { errCh <- proxy.Start(proxyAddr) }()

fmt.Printf("Headroom proxy listening on %s -> %s\n", proxyAddr, proxyUpstream)
fmt.Printf("Set your client base URL to http://localhost%s/v1\n", proxyAddr)

sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

select {
case err := <-errCh:
return err
case <-sigCh:
fmt.Println("\nShutting down proxy...")
return proxy.Shutdown(context.Background())
}
},
}

// headroomLessonsCmd manages the local lessons store.
var headroomLessonsCmd = &cobra.Command{
Use: "lessons",
Short: "Inspect lessons learned from failed sessions",
RunE: func(cmd *cobra.Command, args []string) error {
store, err := headroom.NewLessonStore(lessonsPath)
if err != nil {
return fmt.Errorf("opening lessons store: %w", err)
}

lessons := store.Top(0)
if len(lessons) == 0 {
fmt.Println("No lessons recorded yet.")
return nil
}

fmt.Printf("Lessons (%d):\n", store.Count())
for i, l := range lessons {
fmt.Printf("%d. [%s] weight=%.2f hits=%d\n", i+1, l.Category, l.Weight, l.Hits)
fmt.Printf(" insight: %s\n", l.Insight)
}
return nil
},
}

// headroomLessonsClearCmd removes all recorded lessons.
var headroomLessonsClearCmd = &cobra.Command{
Use: "clear",
Short: "Clear all recorded lessons",
RunE: func(cmd *cobra.Command, args []string) error {
path := lessonsPath
if path == "" {
path = headroom.DefaultLessonsPath()
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("clearing lessons: %w", err)
}
fmt.Println("Lessons cleared.")
return nil
},
}

func init() {
headroomProxyCmd.Flags().StringVar(&proxyAddr, "addr", ":8787", "Address for the proxy to listen on")
headroomProxyCmd.Flags().StringVar(&proxyUpstream, "upstream", "https://api.openai.com", "Upstream OpenAI-compatible base URL")

headroomLessonsCmd.PersistentFlags().StringVar(&lessonsPath, "path", "", "Path to the lessons store file (default ~/.sin-code/headroom/lessons.json)")
headroomLessonsCmd.AddCommand(headroomLessonsClearCmd)

headroomCmd.AddCommand(headroomProxyCmd)
headroomCmd.AddCommand(headroomLessonsCmd)
}
Loading
Loading