Add memory plugin with semantic search and session planning (#145)

* Add memory plugin with semantic search and session planning

* Clarify Memory Plugin is optional in docs
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-23 15:08:56 -05:00
1 parent da283a82cf
commit 3461f86556
132 files changed
+11448 -2834

No files matched your search

-2
View File
@@ -17,8 +17,6 @@ paths-ignore:
- '**/*.spec.tsx'
- 'temp/**'
- '**/*.md'
- '**/test/**'
- '**/__tests__/**'
# Specific files to ignore
files-ignore:
+14
View File
@@ -41,6 +41,7 @@ COPY --chown=node:node package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY --chown=node:node shared/package.json ./shared/
COPY --chown=node:node backend/package.json ./backend/
COPY --chown=node:node frontend/package.json ./frontend/
COPY --chown=node:node packages/memory ./packages/memory/
RUN pnpm install --frozen-lockfile
@@ -52,8 +53,10 @@ COPY backend ./backend
COPY frontend/src ./frontend/src
COPY frontend/public ./frontend/public
COPY frontend/index.html frontend/vite.config.ts frontend/tsconfig*.json frontend/components.json frontend/eslint.config.js ./frontend/
COPY packages/memory ./packages/memory
RUN pnpm --filter frontend build
RUN pnpm --filter @opencode-manager/memory build
FROM base AS runner
@@ -80,6 +83,7 @@ ENV PORT=5003
ENV OPENCODE_SERVER_PORT=5551
ENV DATABASE_PATH=/app/data/opencode.db
ENV WORKSPACE_PATH=/workspace
ENV NODE_PATH=/opt/opencode-plugins/node_modules
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --from=builder /app/shared ./shared
@@ -90,6 +94,16 @@ COPY package.json pnpm-workspace.yaml ./
RUN mkdir -p /app/backend/node_modules/@opencode-manager && \
ln -s /app/shared /app/backend/node_modules/@opencode-manager/shared
COPY --from=builder /app/packages/memory /opt/opencode-plugins/src
RUN cd /opt/opencode-plugins/src && npm install
RUN mkdir -p /opt/opencode-plugins/node_modules/@opencode-manager/memory && \
cp -r /opt/opencode-plugins/src/dist/* /opt/opencode-plugins/node_modules/@opencode-manager/memory/ && \
cp /opt/opencode-plugins/src/package.json /opt/opencode-plugins/node_modules/@opencode-manager/memory/ && \
cp /opt/opencode-plugins/src/config.json /opt/opencode-plugins/node_modules/@opencode-manager/memory/config.json 2>/dev/null || true && \
cp -r /opt/opencode-plugins/src/node_modules/* /opt/opencode-plugins/node_modules/ 2>/dev/null || true
COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
+1
View File
@@ -76,6 +76,7 @@ On first launch, you'll be prompted to create an admin account. That's it!
- **OAuth Support** - Secure OAuth login for Anthropic and GitHub Copilot
- **Custom Agents** - Create agents with custom system prompts and tool permissions
- **MCP Servers** - Add local or remote MCP servers with pre-built templates
- **Memory Plugin** - Persistent project knowledge with semantic search, planning state, and compaction awareness
### Mobile & PWA
- **Mobile-First Design** - Responsive UI optimized for mobile
+118
View File
@@ -0,0 +1,118 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
export interface Migration {
version: number
name: string
up(db: Database): void
down(db: Database): void
}
interface MigrationRecord {
version: number
name: string
applied_at: number
}
function ensureMigrationsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at INTEGER NOT NULL
)
`)
}
function getAppliedVersions(db: Database): Set<number> {
const rows = db.prepare('SELECT version FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
return new Set(rows.map(r => r.version))
}
function markApplied(db: Database, migration: Migration): void {
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)')
.run(migration.version, migration.name, Date.now())
}
function markReverted(db: Database, version: number): void {
db.prepare('DELETE FROM schema_migrations WHERE version = ?').run(version)
}
export function migrate(db: Database, migrations: Migration[]): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations].sort((a, b) => a.version - b.version)
const pending = sorted.filter(m => !applied.has(m.version))
if (pending.length === 0) {
logger.info('Database schema is up to date')
return
}
logger.info(`Running ${pending.length} pending migration(s)`)
for (const migration of pending) {
logger.info(`Applying migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.up(db)
markApplied(db, migration)
db.run('COMMIT')
logger.info(`Migration ${migration.version} applied successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('All migrations applied successfully')
}
export function rollback(db: Database, migrations: Migration[], targetVersion?: number): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations]
.filter(m => applied.has(m.version))
.sort((a, b) => b.version - a.version)
if (sorted.length === 0) {
logger.info('No migrations to rollback')
return
}
const latest = sorted[0]
if (!latest) {
logger.info('No migrations to rollback')
return
}
const target = targetVersion ?? latest.version - 1
const toRevert = sorted.filter(m => m.version > target)
if (toRevert.length === 0) {
logger.info('No migrations to rollback')
return
}
logger.info(`Rolling back ${toRevert.length} migration(s) to version ${target}`)
for (const migration of toRevert) {
logger.info(`Reverting migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.down(db)
markReverted(db, migration.version)
db.run('COMMIT')
logger.info(`Migration ${migration.version} reverted successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Rollback of migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('Rollback completed successfully')
}
-188
View File
@@ -1,188 +0,0 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
interface ColumnInfo {
cid: number
name: string
type: string
notnull: number
dflt_value: unknown
pk: number
}
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find((col: ColumnInfo) => col.name === 'repo_url')
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
logger.info('Migrating repos table to allow nullable repo_url for local repos')
db.run('BEGIN TRANSACTION')
try {
db.run(`
CREATE TABLE repos_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const existingColumns = tableInfo.map((col: ColumnInfo) => col.name)
const columnsToCopy = ['id', 'repo_url', 'local_path', 'branch', 'default_branch', 'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name', 'is_worktree', 'is_local']
.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_new (${columnsStr}) SELECT ${columnsStr} FROM repos`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_new RENAME TO repos')
db.run('COMMIT')
logger.info('Successfully migrated repos table to allow nullable repo_url')
} catch (migrationError) {
db.run('ROLLBACK')
throw migrationError
}
}
const hasBranchColumn = tableInfo.some(col => col.name === 'branch')
if (!hasBranchColumn) {
logger.info('Adding missing branch column to repos table')
db.run('ALTER TABLE repos ADD COLUMN branch TEXT')
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_repo_url_branch
ON repos(repo_url, branch)
WHERE branch IS NOT NULL
`)
} catch (error) {
logger.warn('Index already exists or could not be created', error)
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path
ON repos(local_path)
`)
} catch (error) {
logger.warn('Local path index already exists or could not be created', error)
}
const requiredColumns = [
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' }
]
for (const column of requiredColumns) {
const hasColumn = tableInfo.some(col => col.name === column.name)
if (!hasColumn) {
logger.info(`Adding missing column: ${column.name}`)
try {
db.run(column.sql)
} catch (error) {
logger.debug(`Column ${column.name} might already exist:`, error)
}
}
}
const indexes = [
'CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)',
'CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)'
]
for (const indexSql of indexes) {
try {
db.run(indexSql)
} catch (error) {
logger.warn('Index already exists:', error)
}
}
try {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length > 0) {
logger.info(`Migrating ${repos.length} repos to remove 'repos/' prefix from local_path`)
const updateStmt = db.prepare("UPDATE repos SET local_path = ? WHERE id = ?")
for (const repo of repos) {
const newPath = repo.local_path.replace(/^repos\//, '')
updateStmt.run(newPath, repo.id)
logger.info(`Updated repo ${repo.id}: ${repo.local_path} -> ${newPath}`)
}
}
} catch (error) {
logger.error('Failed to migrate local_path format:', error)
}
migrateGitTokenToCredentials(db)
logger.info('Database migrations completed successfully')
} catch (error) {
logger.error('Failed to run database migrations:', error)
throw error
}
}
function migrateGitTokenToCredentials(db: Database): void {
try {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const gitToken = parsed.gitToken as string | undefined
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
if (!gitToken) {
continue
}
if (existingCredentials && existingCredentials.length > 0) {
continue
}
const { gitToken: _, ...rest } = parsed
void _
const migrated = {
...rest,
gitCredentials: [{
name: 'GitHub',
host: 'https://github.com/',
token: gitToken,
}],
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(migrated), row.user_id)
logger.info(`Migrated gitToken to gitCredentials for user: ${row.user_id}`)
} catch (parseError) {
logger.error(`Failed to parse preferences for user ${row.user_id}:`, parseError)
}
}
} catch (error) {
logger.error('Failed to migrate gitToken to gitCredentials:', error)
}
}
@@ -0,0 +1,177 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 1,
name: 'base-schema',
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
db.run(`
CREATE TABLE IF NOT EXISTS user_preferences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
preferences TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id)')
db.run(`
CREATE TABLE IF NOT EXISTS opencode_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
config_name TEXT NOT NULL,
config_content TEXT NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, config_name)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)')
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)')
db.run(`
CREATE TABLE IF NOT EXISTS "user" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
emailVerified INTEGER NOT NULL DEFAULT 0,
image TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
role TEXT DEFAULT 'user'
)
`)
db.run(`
CREATE TABLE IF NOT EXISTS "session" (
id TEXT PRIMARY KEY NOT NULL,
expiresAt INTEGER NOT NULL,
token TEXT NOT NULL UNIQUE,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
ipAddress TEXT,
userAgent TEXT,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_session_userId ON "session"(userId)')
db.run('CREATE INDEX IF NOT EXISTS idx_session_token ON "session"(token)')
db.run(`
CREATE TABLE IF NOT EXISTS "account" (
id TEXT PRIMARY KEY NOT NULL,
accountId TEXT NOT NULL,
providerId TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
accessToken TEXT,
refreshToken TEXT,
idToken TEXT,
accessTokenExpiresAt INTEGER,
refreshTokenExpiresAt INTEGER,
scope TEXT,
password TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_account_userId ON "account"(userId)')
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_account_provider ON "account"(providerId, accountId)')
db.run(`
CREATE TABLE IF NOT EXISTS "verification" (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expiresAt INTEGER NOT NULL,
createdAt INTEGER,
updatedAt INTEGER
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_verification_identifier ON "verification"(identifier)')
db.run(`
CREATE TABLE IF NOT EXISTS "passkey" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT,
publicKey TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
credentialID TEXT NOT NULL,
counter INTEGER NOT NULL,
deviceType TEXT NOT NULL,
backedUp INTEGER NOT NULL DEFAULT 0,
transports TEXT,
createdAt INTEGER,
aaguid TEXT
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId)')
db.run('CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID)')
db.run(`
CREATE TABLE IF NOT EXISTS trusted_ssh_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
host TEXT NOT NULL UNIQUE,
key_type TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_trusted_ssh_hosts_host ON trusted_ssh_hosts(host)')
db.run(`
CREATE TABLE IF NOT EXISTS repo_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(repo_id, key)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_repo_settings_repo ON repo_settings(repo_id)')
},
down(db) {
db.run('DROP TABLE IF EXISTS repo_settings')
db.run('DROP TABLE IF EXISTS trusted_ssh_hosts')
db.run('DROP TABLE IF EXISTS "passkey"')
db.run('DROP TABLE IF EXISTS "verification"')
db.run('DROP TABLE IF EXISTS "account"')
db.run('DROP TABLE IF EXISTS "session"')
db.run('DROP TABLE IF EXISTS "user"')
db.run('DROP TABLE IF EXISTS opencode_configs')
db.run('DROP TABLE IF EXISTS user_preferences')
db.run('DROP TABLE IF EXISTS repos')
},
}
export default migration
@@ -0,0 +1,84 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
notnull: number
}
const migration: Migration = {
version: 2,
name: 'repos-nullable-url',
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find(col => col.name === 'repo_url')
if (!repoUrlColumn || repoUrlColumn.notnull !== 1) return
const existingColumns = tableInfo.map(col => col.name)
db.run(`
CREATE TABLE repos_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const targetColumns = [
'id', 'repo_url', 'local_path', 'branch', 'default_branch',
'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name',
'is_worktree', 'is_local'
]
const columnsToCopy = targetColumns.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_new (${columnsStr}) SELECT ${columnsStr} FROM repos`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_new RENAME TO repos')
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
},
down(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const existingColumns = tableInfo.map(col => col.name)
db.run(`
CREATE TABLE repos_old (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT NOT NULL,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const targetColumns = [
'id', 'repo_url', 'local_path', 'branch', 'default_branch',
'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name',
'is_worktree', 'is_local'
]
const columnsToCopy = targetColumns.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_old (${columnsStr}) SELECT ${columnsStr} FROM repos WHERE repo_url IS NOT NULL`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_old RENAME TO repos')
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
},
}
export default migration
@@ -0,0 +1,38 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
}
const COLUMNS = [
{ name: 'branch', sql: 'ALTER TABLE repos ADD COLUMN branch TEXT' },
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' },
]
const migration: Migration = {
version: 3,
name: 'repos-add-columns',
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const existing = new Set(tableInfo.map(col => col.name))
for (const col of COLUMNS) {
if (!existing.has(col.name)) {
db.run(col.sql)
}
}
},
down(db) {
void db
},
}
export default migration
@@ -0,0 +1,22 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 4,
name: 'repos-indexes',
up(db) {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_repo_url_branch
ON repos(repo_url, branch)
WHERE branch IS NOT NULL
`)
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path ON repos(local_path)')
},
down(db) {
db.run('DROP INDEX IF EXISTS idx_repo_url_branch')
db.run('DROP INDEX IF EXISTS idx_local_path')
},
}
export default migration
@@ -0,0 +1,28 @@
import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 5,
name: 'repos-local-path-prefix',
up(db) {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length === 0) return
logger.info(`Stripping 'repos/' prefix from ${repos.length} repo local_path(s)`)
const stmt = db.prepare('UPDATE repos SET local_path = ? WHERE id = ?')
for (const repo of repos) {
stmt.run(repo.local_path.replace(/^repos\//, ''), repo.id)
}
},
down(db) {
void db
},
}
export default migration
@@ -0,0 +1,74 @@
import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 6,
name: 'git-token-to-credentials',
up(db) {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const gitToken = parsed.gitToken as string | undefined
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
if (!gitToken) continue
if (existingCredentials && existingCredentials.length > 0) continue
const { gitToken: _, ...rest } = parsed
void _
const migrated = {
...rest,
gitCredentials: [{
name: 'GitHub',
host: 'https://github.com/',
token: gitToken,
}],
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(migrated), row.user_id)
logger.info(`Migrated gitToken to gitCredentials for user: ${row.user_id}`)
} catch (parseError) {
logger.error(`Failed to parse preferences for user ${row.user_id}:`, parseError)
}
}
},
down(db) {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const credentials = parsed.gitCredentials as Array<{ token: string }> | undefined
const firstCredential = credentials?.[0]
if (!firstCredential) continue
const { gitCredentials: _, ...rest } = parsed
void _
const reverted = {
...rest,
gitToken: firstCredential.token,
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(reverted), row.user_id)
} catch (parseError) {
logger.error(`Failed to revert preferences for user ${row.user_id}:`, parseError)
}
}
},
}
export default migration
+16
View File
@@ -0,0 +1,16 @@
import type { Migration } from '../migration-runner'
import migration001 from './001-base-schema'
import migration002 from './002-repos-nullable-url'
import migration003 from './003-repos-add-columns'
import migration004 from './004-repos-indexes'
import migration005 from './005-repos-local-path-prefix'
import migration006 from './006-git-token-to-credentials'
export const allMigrations: Migration[] = [
migration001,
migration002,
migration003,
migration004,
migration005,
migration006,
]
-7
View File
@@ -94,13 +94,6 @@ export function getRepoById(db: Database, id: number): Repo | null {
return row ? rowToRepo(row) : null
}
export function getRepoByUrl(db: Database, repoUrl: string): Repo | null {
const stmt = db.prepare('SELECT * FROM repos WHERE repo_url = ?')
const row = stmt.get(repoUrl) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null {
const query = branch
? 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?'
+5 -130
View File
@@ -2,144 +2,19 @@ import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import { mkdirSync } from 'fs'
import { dirname } from 'path'
import { runMigrations } from './migrations'
import { migrate } from './migration-runner'
import { allMigrations } from './migrations'
export function initializeDatabase(dbPath: string = './data/opencode.db'): Database {
mkdirSync(dirname(dbPath), { recursive: true })
const db = new Database(dbPath)
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status);
CREATE TABLE IF NOT EXISTS user_preferences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
preferences TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id)
);
CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id);
CREATE TABLE IF NOT EXISTS opencode_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
config_name TEXT NOT NULL,
config_content TEXT NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, config_name)
);
CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id);
CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default);
-- Better Auth tables
CREATE TABLE IF NOT EXISTS "user" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
emailVerified INTEGER NOT NULL DEFAULT 0,
image TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
role TEXT DEFAULT 'user'
);
CREATE TABLE IF NOT EXISTS "session" (
id TEXT PRIMARY KEY NOT NULL,
expiresAt INTEGER NOT NULL,
token TEXT NOT NULL UNIQUE,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
ipAddress TEXT,
userAgent TEXT,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_session_userId ON "session"(userId);
CREATE INDEX IF NOT EXISTS idx_session_token ON "session"(token);
CREATE TABLE IF NOT EXISTS "account" (
id TEXT PRIMARY KEY NOT NULL,
accountId TEXT NOT NULL,
providerId TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
accessToken TEXT,
refreshToken TEXT,
idToken TEXT,
accessTokenExpiresAt INTEGER,
refreshTokenExpiresAt INTEGER,
scope TEXT,
password TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_account_userId ON "account"(userId);
CREATE UNIQUE INDEX IF NOT EXISTS idx_account_provider ON "account"(providerId, accountId);
CREATE TABLE IF NOT EXISTS "verification" (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expiresAt INTEGER NOT NULL,
createdAt INTEGER,
updatedAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_verification_identifier ON "verification"(identifier);
CREATE TABLE IF NOT EXISTS "passkey" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT,
publicKey TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
credentialID TEXT NOT NULL,
counter INTEGER NOT NULL,
deviceType TEXT NOT NULL,
backedUp INTEGER NOT NULL DEFAULT 0,
transports TEXT,
createdAt INTEGER,
aaguid TEXT
);
CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId);
CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID);
CREATE TABLE IF NOT EXISTS trusted_ssh_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
host TEXT NOT NULL UNIQUE,
key_type TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
migrate(db, allMigrations)
CREATE INDEX IF NOT EXISTS idx_trusted_ssh_hosts_host ON trusted_ssh_hosts(host);
`)
runMigrations(db)
db.prepare('INSERT OR IGNORE INTO user_preferences (user_id, preferences, updated_at) VALUES (?, ?, ?)')
.run('default', '{}', Date.now())
logger.info('Database initialized successfully')
return db
}
+3
View File
@@ -31,6 +31,7 @@ import { createTitleRoutes } from './routes/title'
import { createSSERoutes } from './routes/sse'
import { createSSHRoutes } from './routes/ssh'
import { createNotificationRoutes } from './routes/notifications'
import { createMemoryRoutes } from './routes/memory'
import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
@@ -41,6 +42,7 @@ import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { NotificationService } from './services/notification'
import { logger } from './utils/logger'
import {
getWorkspacePath,
@@ -254,6 +256,7 @@ protectedApi.route('/generate-title', createTitleRoutes())
protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/memory', createMemoryRoutes(db))
app.route('/api', protectedApi)
+1 -15
View File
@@ -2,25 +2,11 @@ import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { readFile } from 'fs/promises'
import { opencodeServerManager } from '../services/opencode-single-server'
import { compareVersions } from '../utils/version-utils'
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
const GITHUB_REPO_NAME = 'opencode-manager'
function compareVersions(a: string, b: string): number {
const cleanA = a.replace(/^v/, '')
const cleanB = b.replace(/^v/, '')
const partsA = cleanA.split('.').map(Number)
const partsB = cleanB.split('.').map(Number)
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const partA = partsA[i] ?? 0
const partB = partsB[i] ?? 0
if (partA > partB) return 1
if (partA < partB) return -1
}
return 0
}
interface CachedRelease {
tagName: string
htmlUrl: string
+446
View File
@@ -0,0 +1,446 @@
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'
import { logger } from '../utils/logger'
import { PluginMemoryService } from '../services/plugin-memory'
import { resolveProjectId } from '../services/project-id-resolver'
import { getRepoById } from '../db/queries'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import {
CreateMemoryRequestSchema,
UpdateMemoryRequestSchema,
MemoryListQuerySchema,
PluginConfigSchema,
type PluginConfig,
} from '@opencode-manager/shared/schemas'
function resolveMemoryDataDir(): string {
return join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory')
}
function resolvePluginConfigPath(): string {
return join(resolveMemoryDataDir(), 'config.json')
}
function getDefaultPluginConfig(): PluginConfig {
return {
embedding: {
provider: 'local',
model: 'all-MiniLM-L6-v2',
dimensions: 384,
},
dedupThreshold: 0.25,
}
}
function loadPluginConfigFromDisk(): PluginConfig {
const configPath = resolvePluginConfigPath()
if (!existsSync(configPath)) {
return getDefaultPluginConfig()
}
try {
const content = readFileSync(configPath, 'utf-8')
const parsed = JSON.parse(content)
const result = PluginConfigSchema.safeParse(parsed)
if (!result.success) {
logger.error('Invalid plugin config:', result.error)
return getDefaultPluginConfig()
}
return result.data
} catch (error) {
logger.error('Failed to load plugin config:', error)
return getDefaultPluginConfig()
}
}
function savePluginConfigToDisk(config: PluginConfig): void {
const configPath = resolvePluginConfigPath()
const dataDir = resolveMemoryDataDir()
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
}
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8')
}
export function createMemoryRoutes(db: Database): Hono {
const app = new Hono()
const pluginMemory = new PluginMemoryService()
app.get('/', async (c) => {
const query = c.req.query()
const parsed = MemoryListQuerySchema.safeParse({
projectId: query.projectId,
scope: query.scope,
content: query.content,
limit: query.limit ? parseInt(query.limit, 10) : undefined,
offset: query.offset ? parseInt(query.offset, 10) : undefined,
})
if (!parsed.success) {
return c.json({ error: 'Invalid query parameters', details: parsed.error }, 400)
}
const filters = parsed.data
if (!filters.projectId) {
return c.json({ memories: [] })
}
const memories = pluginMemory.list(filters.projectId, {
scope: filters.scope,
content: filters.content,
limit: filters.limit,
offset: filters.offset,
})
return c.json({ memories })
})
app.post('/', async (c) => {
const body = await c.req.json()
const parsed = CreateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
const id = pluginMemory.create(parsed.data)
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Failed to retrieve created memory' }, 500)
}
return c.json({ memory }, 201)
} catch (error) {
logger.error('Failed to create memory:', error)
return c.json({ error: 'Failed to create memory' }, 500)
}
})
app.get('/project-summary', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} } })
}
const stats = pluginMemory.getStats(projectId)
return c.json({ projectId, stats })
} catch (error) {
logger.error('Failed to get project summary:', error)
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Failed to get project summary' }, 500)
}
})
app.get('/stats', async (c) => {
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
try {
const stats = pluginMemory.getStats(projectId)
return c.json(stats)
} catch (error) {
logger.error('Failed to get memory stats:', error)
return c.json({ error: 'Failed to get stats' }, 500)
}
})
app.get('/resolve-project', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
return c.json({ projectId })
} catch (error) {
logger.error('Failed to resolve project ID:', error)
return c.json({ projectId: null, error: 'Failed to resolve project ID' }, 500)
}
})
app.get('/plugin-config', async (c) => {
try {
const config = loadPluginConfigFromDisk()
return c.json({ config })
} catch (error) {
logger.error('Failed to get plugin config:', error)
return c.json({ error: 'Failed to get plugin config' }, 500)
}
})
app.put('/plugin-config', async (c) => {
try {
const body = await c.req.json()
const parsed = PluginConfigSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid config', details: parsed.error.flatten() }, 400)
}
const config = parsed.data
config.dedupThreshold = Math.max(0.05, Math.min(0.4, config.dedupThreshold ?? 0.25))
savePluginConfigToDisk(config)
return c.json({ success: true, config })
} catch (error) {
logger.error('Failed to save plugin config:', error)
return c.json({ error: 'Failed to save plugin config' }, 500)
}
})
app.post('/test-embedding', async (c) => {
try {
const config = loadPluginConfigFromDisk()
if (config.embedding.provider === 'local') {
const validModels = ['all-MiniLM-L6-v2']
if (!validModels.includes(config.embedding.model)) {
return c.json({
success: false,
error: `Invalid model: ${config.embedding.model}. Valid models: ${validModels.join(', ')}`
}, 400)
}
return c.json({
success: true,
message: 'Local provider configured. Model will be loaded on server restart.',
dimensions: config.embedding.dimensions ?? 384,
})
}
const endpoints: Record<string, string> = {
openai: 'https://api.openai.com/v1/embeddings',
voyage: 'https://api.voyageai.com/v1/embeddings',
}
const extractHost = (url: string): string => {
const protocolEnd = url.indexOf('://')
if (protocolEnd === -1) return url
const pathStart = url.indexOf('/', protocolEnd + 3)
return pathStart === -1 ? url : url.slice(0, pathStart)
}
const baseUrl = extractHost(config.embedding.baseUrl || '')
const endpoint = baseUrl
? `${baseUrl}/v1/embeddings`
: endpoints[config.embedding.provider] ?? ''
if (!endpoint) {
return c.json({ success: false, error: 'No endpoint configured' }, 400)
}
if (!config.embedding.apiKey) {
return c.json({ success: false, error: 'API key not configured. Please save your API key first.' }, 400)
}
const testBody = {
model: config.embedding.model,
input: ['test'],
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.embedding.apiKey}`,
}
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(testBody),
})
if (!response.ok) {
const errorText = await response.text()
return c.json({
success: false,
error: `API error: ${response.status}`,
message: errorText,
}, 400)
}
const data = await response.json() as {
data?: Array<{ embedding: number[] }>
embeddings?: Array<{ embedding: number[] }>
}
const embeddings = data.data || data.embeddings
if (!embeddings || embeddings.length === 0 || !embeddings[0]) {
return c.json({ success: false, error: 'Invalid response from API' }, 400)
}
const firstEmbedding = embeddings[0]
const actualDimensions = firstEmbedding.embedding.length
return c.json({
success: true,
message: `Embedding test successful. Generated ${actualDimensions}d embedding.`,
dimensions: actualDimensions,
})
} catch (error) {
logger.error('Failed to test embedding config:', error)
return c.json({
success: false,
error: 'Failed to test embedding configuration',
message: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.get('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Memory not found' }, 404)
}
return c.json({ memory })
})
app.put('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const body = await c.req.json()
const parsed = UpdateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.update(id, parsed.data)
const memory = pluginMemory.getById(id)
return c.json({ memory })
} catch (error) {
logger.error('Failed to update memory:', error)
return c.json({ error: 'Failed to update memory' }, 500)
}
})
app.delete('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
try {
pluginMemory.delete(id)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete memory:', error)
return c.json({ error: 'Failed to delete memory' }, 500)
}
})
app.post('/reindex', async (c) => {
try {
const db = pluginMemory.getDb()
if (!db) {
return c.json({
error: 'Memory database not found. Make sure the memory plugin has been initialized.',
total: 0,
embedded: 0,
failed: 0
}, 404)
}
const memories = pluginMemory.listAll()
if (memories.length === 0) {
return c.json({
success: true,
message: 'No memories to reindex',
total: 0,
embedded: 0,
failed: 0
})
}
try {
db.exec('DELETE FROM memory_embeddings')
} catch {
return c.json({
success: true,
message: 'Cleared embeddings. Server restart required to regenerate embeddings with new model.',
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
}
return c.json({
success: true,
message: `Cleared ${memories.length} embeddings. Server restart required to regenerate embeddings.`,
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
} catch (error) {
logger.error('Failed to reindex memories:', error)
return c.json({ error: 'Failed to reindex memories', details: error instanceof Error ? error.message : 'Unknown error' }, 500)
}
})
return app
}
-92
View File
@@ -303,98 +303,6 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
}
})
app.post('/:id/git/discard', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const { paths, staged } = body
if (!paths || !Array.isArray(paths)) {
return c.json({ error: 'paths is required and must be an array' }, 400)
}
await git.discardChanges(id, paths, staged ?? false, database)
const status = await git.getStatus(id, database)
return c.json(status)
} catch (error: unknown) {
logger.error('Failed to discard changes:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/commit/:hash', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const hash = c.req.param('hash')
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
if (!hash) {
return c.json({ error: 'hash is required' }, 400)
}
const commitDetails = await git.getCommitDetails(id, hash, database)
if (!commitDetails) {
return c.json({ error: 'Commit not found' }, 404)
}
return c.json(commitDetails)
} catch (error: unknown) {
logger.error('Failed to get commit details:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/commit/:hash/diff', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const hash = c.req.param('hash')
const filePath = c.req.query('path')
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
if (!hash) {
return c.json({ error: 'hash is required' }, 400)
}
if (!filePath) {
return c.json({ error: 'path query parameter is required' }, 400)
}
const diff = await git.getCommitDiff(id, hash, filePath, database)
return c.json(diff)
} catch (error: unknown) {
logger.error('Failed to get commit diff:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/log', async (c) => {
try {
const id = parseInt(c.req.param('id'))
+14 -13
View File
@@ -18,19 +18,7 @@ import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../constants'
import { validateSSHPrivateKey } from '../utils/ssh-validation'
import { encryptSecret } from '../utils/crypto'
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(s => Number(s))
const parts2 = v2.split('.').map(s => Number(s))
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0
const p2 = parts2[i] || 0
if (p1 > p2) return 1
if (p1 < p2) return -1
}
return 0
}
import { compareVersions } from '../utils/version-utils'
function getOpenCodeInstallMethod(): string {
const homePath = process.env.HOME || ''
@@ -156,6 +144,19 @@ export function createSettingsRoutes(db: Database) {
}
})
app.get('/memory-plugin-status', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configs = settingsService.getOpenCodeConfigs(userId)
const defaultConfig = configs.configs.find((cfg: { isDefault: boolean }) => cfg.isDefault)
const isEnabled = defaultConfig?.content?.plugin?.includes('@opencode-manager/memory') ?? false
return c.json({ memoryPluginEnabled: isEnabled })
} catch (error) {
logger.error('Failed to get memory plugin status:', error)
return c.json({ error: 'Failed to get memory plugin status' }, 500)
}
})
app.patch('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
+3 -263
View File
@@ -7,7 +7,7 @@ import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../../utils/
import { isNoUpstreamError, parseBranchNameFromError } from '../../utils/git-errors'
import { SettingsService } from '../settings'
import type { Database } from 'bun:sqlite'
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git'
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType } from '../../types/git'
import type { GitCredential } from '@opencode-manager/shared'
import path from 'path'
@@ -269,252 +269,6 @@ export class GitService {
}
}
async discardChanges(repoId: number, paths: string[], staged: boolean, database: Database): Promise<string> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const repoPath = repo.fullPath
const env = this.gitAuthService.getGitEnvironment()
if (paths.length === 0) {
return ''
}
if (staged) {
const args = ['git', '-C', repoPath, 'restore', '--staged', '--worktree', '--source', 'HEAD', '--', ...paths]
return await executeCommand(args, { env })
}
const statusOutput = await executeCommand(
['git', '-C', repoPath, 'status', '--porcelain', '-u', '--', ...paths],
{ env }
)
const untrackedPaths: string[] = []
const trackedPaths: string[] = []
for (const line of statusOutput.split('\n')) {
if (!line.trim()) continue
const statusCode = line.substring(0, 2)
const filePath = line.substring(3).trim()
if (statusCode === '??') {
untrackedPaths.push(filePath)
} else {
trackedPaths.push(filePath)
}
}
const results: string[] = []
if (trackedPaths.length > 0) {
const args = ['git', '-C', repoPath, 'checkout', '--', ...trackedPaths]
results.push(await executeCommand(args, { env }))
}
if (untrackedPaths.length > 0) {
try {
const args = ['git', '-C', repoPath, 'clean', '-fd', '--', ...untrackedPaths]
results.push(await executeCommand(args, { env }))
} catch (error: unknown) {
logger.error(`Failed to clean untracked files for repo ${repoId}:`, error)
throw error
}
}
return results.join('\n')
} catch (error: unknown) {
logger.error(`Failed to discard changes for repo ${repoId}:`, error)
throw error
}
}
private normalizeRenamePath(path: string): string {
const renamePattern = /\{[^=]+=>\s*([^}]+)\}/
let normalized = path
while (renamePattern.test(normalized)) {
normalized = normalized.replace(renamePattern, '$1')
}
return normalized.trim()
}
private parseNumstatOutput(output: string): Map<string, { additions: number; deletions: number }> {
const map = new Map<string, { additions: number; deletions: number }>()
const lines = output.trim().split('\n')
for (const line of lines) {
if (!line.trim()) continue
const parts = line.split('\t')
if (parts.length >= 3) {
const additions = parts[0]
const deletions = parts[1]
const filePath = parts.slice(2).join('\t')
const normalizedPath = this.normalizeRenamePath(filePath)
if (
additions?.match(/^\d+$/) &&
deletions?.match(/^\d+$/) &&
normalizedPath
) {
map.set(normalizedPath, {
additions: parseInt(additions, 10),
deletions: parseInt(deletions, 10)
})
}
}
}
return map
}
private parseCommitFiles(
output: string,
numstatMap: Map<string, { additions: number; deletions: number }>
): CommitFile[] {
const files: CommitFile[] = []
const lines = output.trim().split('\n')
for (const line of lines) {
if (!line.trim()) continue
const parts = line.split('\t')
if (parts.length >= 2 && parts[0] && parts[0].match(/^[AMDRC]/)) {
const statusCode = parts[0]
const fromPath = parts[1] || ''
const toPath = parts[2] || parts[1] || ''
const isRename = statusCode.startsWith('R')
const isCopy = statusCode.startsWith('C')
let status: GitFileStatusType = 'modified'
switch (statusCode.charAt(0)) {
case 'A':
status = 'added'
break
case 'D':
status = 'deleted'
break
case 'R':
status = 'renamed'
break
case 'C':
status = 'copied'
break
case 'M':
status = 'modified'
break
}
const numstatData = numstatMap.get(toPath)
const additions = numstatData?.additions ?? 0
const deletions = numstatData?.deletions ?? 0
files.push({
path: toPath,
status,
oldPath: isRename || isCopy ? fromPath : undefined,
additions,
deletions
})
}
}
return files
}
async getCommitDetails(repoId: number, hash: string, database: Database): Promise<CommitDetails | null> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(true)
const commitOutput = await executeCommand(
['git', '-C', repoPath, 'log', '-1', '--format=%H%x00%an%x00%ae%x00%at%x00%B', hash],
{ env }
)
if (!commitOutput.trim()) {
return null
}
const parts = commitOutput.trim().split('\0')
const [commitHash, authorName, authorEmail, timestamp, message] = parts
if (!commitHash) {
return null
}
const filesOutput = await executeCommand(
['git', '-C', repoPath, 'show', '-M', '--name-status', '--format=', hash],
{ env }
)
const numstatOutput = await executeCommand(
['git', '-C', repoPath, 'show', '-M', '--numstat', '--format=', hash],
{ env }
)
const numstatMap = this.parseNumstatOutput(numstatOutput)
const files = this.parseCommitFiles(filesOutput, numstatMap)
return {
hash: commitHash,
authorName: authorName || '',
authorEmail: authorEmail || '',
date: timestamp || '',
message: message || '',
unpushed: await this.isCommitUnpushed(repoPath, commitHash, env),
files
}
} catch (error: unknown) {
logger.error(`Failed to get commit details for repo ${repoId}:`, error)
throw new Error(`Failed to get commit details: ${getErrorMessage(error)}`)
}
}
async getCommitDiff(repoId: number, hash: string, filePath: string, database: Database): Promise<FileDiffResponse> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(true)
const diff = await executeCommand(
['git', '-C', repoPath, 'show', '--format=', hash, '--', filePath],
{ env }
)
const status = this.detectDiffStatus(diff)
return this.parseDiffOutput(diff, status, filePath)
} catch (error: unknown) {
logger.error(`Failed to get commit diff for repo ${repoId}:`, error)
throw new Error(`Failed to get commit diff: ${getErrorMessage(error)}`)
}
}
private detectDiffStatus(diff: string): GitFileStatusType {
if (diff.includes('new file mode')) {
return 'added'
}
if (diff.includes('deleted file mode')) {
return 'deleted'
}
if (diff.includes('rename from') || diff.includes('rename to')) {
return 'renamed'
}
return 'modified'
}
private async setupSSHIfNeeded(repoUrl: string | undefined, database: Database): Promise<void> {
await this.gitAuthService.setupSSHForRepoUrl(repoUrl, database)
}
@@ -915,7 +669,6 @@ export class GitService {
let additions = 0
let deletions = 0
let isBinary = false
const MAX_DIFF_SIZE = 500 * 1024
if (typeof diff === 'string') {
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
@@ -929,21 +682,13 @@ export class GitService {
}
}
let diffOutput = typeof diff === 'string' ? diff : ''
let truncated = false
if (diffOutput.length > MAX_DIFF_SIZE) {
diffOutput = diffOutput.substring(0, MAX_DIFF_SIZE) + '\n\n... (diff truncated due to size)'
truncated = true
}
return {
path: filePath || '',
status: status as GitFileStatusType,
diff: diffOutput,
diff: typeof diff === 'string' ? diff : '',
additions,
deletions,
isBinary,
truncated
isBinary
}
}
@@ -956,11 +701,6 @@ export class GitService {
}
}
private async isCommitUnpushed(repoPath: string, commitHash: string, env: Record<string, string>): Promise<boolean> {
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, env)
return unpushedHashes.has(commitHash)
}
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
try {
const output = await executeCommand(
+1 -13
View File
@@ -17,6 +17,7 @@ import { decryptSecret } from '../utils/crypto'
import { SettingsService } from './settings'
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { compareVersions } from '../utils/version-utils'
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
@@ -25,19 +26,6 @@ const OPENCODE_CONFIG_PATH = getOpenCodeConfigFilePath()
const MIN_OPENCODE_VERSION = '1.0.137'
const MAX_STDERR_SIZE = 10240
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(Number)
const parts2 = v2.split('.').map(Number)
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0
const p2 = parts2[i] || 0
if (p1 > p2) return 1
if (p1 < p2) return -1
}
return 0
}
class OpenCodeServerManager {
private static instance: OpenCodeServerManager
private serverProcess: ReturnType<typeof spawn> | null = null
+242
View File
@@ -0,0 +1,242 @@
import { Database } from 'bun:sqlite'
import path from 'path'
import { existsSync } from 'node:fs'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
export interface PluginMemory {
id: number
projectId: string
scope: 'convention' | 'decision' | 'context'
content: string
filePath: string | null
accessCount: number
lastAccessedAt: number | null
createdAt: number
updatedAt: number
}
interface DbMemoryRow {
id: number
project_id: string
scope: string
content: string
file_path: string | null
access_count: number
last_accessed_at: number | null
created_at: number
updated_at: number
}
interface MemoryFilters {
scope?: 'convention' | 'decision' | 'context'
content?: string
limit?: number
offset?: number
}
function getPluginDbPath(): string {
return path.join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
}
function mapRowToMemory(row: DbMemoryRow): PluginMemory {
return {
id: row.id,
projectId: row.project_id,
scope: row.scope as PluginMemory['scope'],
content: row.content,
filePath: row.file_path,
accessCount: row.access_count,
lastAccessedAt: row.last_accessed_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
export class PluginMemoryService {
private db: Database | null = null
getDb(): Database | null {
if (this.db) return this.db
const dbPath = getPluginDbPath()
if (!existsSync(dbPath)) {
return null
}
try {
this.db = new Database(dbPath)
this.db.exec('PRAGMA journal_mode = WAL')
return this.db
} catch {
return null
}
}
list(projectId: string, filters?: MemoryFilters): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE project_id = ?'
const params: (string | number)[] = [projectId]
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
if (filters?.content) {
sql += ' AND content LIKE ?'
params.push(`%${filters.content}%`)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
listAll(filters?: { projectId?: string; scope?: string; limit?: number; offset?: number }): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE 1=1'
const params: (string | number)[] = []
if (filters?.projectId) {
sql += ' AND project_id = ?'
params.push(filters.projectId)
}
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
getById(id: number): PluginMemory | undefined {
const db = this.getDb()
if (!db) return undefined
const stmt = db.prepare('SELECT * FROM memories WHERE id = ?')
const row = stmt.get(id) as DbMemoryRow | undefined
return row ? mapRowToMemory(row) : undefined
}
create(input: { projectId: string; scope: string; content: string }): number {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const now = Date.now()
const stmt = db.prepare(`
INSERT INTO memories (project_id, scope, content, access_count, created_at, updated_at)
VALUES (?, ?, ?, 0, ?, ?)
`)
const result = stmt.run(input.projectId, input.scope, input.content, now, now)
return result.lastInsertRowid as number
}
update(id: number, input: { content?: string; scope?: string }): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const updates: string[] = []
const params: (string | number)[] = []
if (input.content !== undefined) {
updates.push('content = ?')
params.push(input.content)
}
if (input.scope !== undefined) {
updates.push('scope = ?')
params.push(input.scope)
}
if (updates.length === 0) return
updates.push('updated_at = ?')
params.push(Date.now())
params.push(id)
const sql = `UPDATE memories SET ${updates.join(', ')} WHERE id = ?`
const stmt = db.prepare(sql)
stmt.run(...params)
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
}
delete(id: number): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
const stmt = db.prepare('DELETE FROM memories WHERE id = ?')
stmt.run(id)
}
getStats(projectId: string): { projectId: string; total: number; byScope: Record<string, number> } {
const db = this.getDb()
if (!db) {
return { projectId, total: 0, byScope: {} }
}
const totalStmt = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?')
const totalResult = totalStmt.get(projectId) as { count: number }
const total = totalResult.count
const byScopeStmt = db.prepare('SELECT scope, COUNT(*) as count FROM memories WHERE project_id = ? GROUP BY scope')
const byScopeRows = byScopeStmt.all(projectId) as { scope: string; count: number }[]
const byScope: Record<string, number> = {}
for (const row of byScopeRows) {
byScope[row.scope] = row.count
}
return { projectId, total, byScope }
}
close(): void {
if (this.db) {
this.db.close()
this.db = null
}
}
}
@@ -0,0 +1,68 @@
import { exec } from 'child_process'
import { readFile } from 'fs/promises'
import { fileExists } from './file-operations'
const projectIdCache = new Map<string, string>()
async function executeGitCommand(cwd: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
exec('git ' + args.join(' '), { cwd }, (error, stdout) => {
if (error) {
reject(error)
} else {
resolve(stdout.trim())
}
})
})
}
export async function resolveProjectId(repoFullPath: string): Promise<string | null> {
if (projectIdCache.has(repoFullPath)) {
return projectIdCache.get(repoFullPath) ?? null
}
const cacheFile = `${repoFullPath}/.git/opencode`
const cacheExists = await fileExists(cacheFile)
if (cacheExists) {
try {
const cachedId = (await readFile(cacheFile, 'utf-8')).trim()
if (cachedId) {
projectIdCache.set(repoFullPath, cachedId)
return cachedId
}
} catch {
// cache file may not exist or be readable
}
}
try {
const gitDir = `${repoFullPath}/.git`
const gitDirExists = await fileExists(gitDir)
if (!gitDirExists) {
return null
}
const output = await executeGitCommand(repoFullPath, [
'rev-list',
'--max-parents=0',
'--all',
])
if (!output) {
return null
}
const commits = output.split('\n').filter(Boolean).sort()
const projectId = commits[0]
if (!projectId) {
return null
}
projectIdCache.set(repoFullPath, projectId)
return projectId
} catch {
return null
}
}
+6 -28
View File
@@ -9,6 +9,7 @@ import type { GitAuthService } from './git-auth'
import { isGitHubHttpsUrl, isSSHUrl, normalizeSSHUrl } from '../utils/git-auth'
import path from 'path'
import { parseSSHHost } from '../utils/ssh-key-manager'
import { getErrorMessage } from '../utils/error-utils'
const GIT_CLONE_TIMEOUT = 300000
@@ -38,29 +39,6 @@ function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: str
return error instanceof Error ? error : new Error(originalMessage)
}
interface ErrorWithMessage {
message: string
}
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as ErrorWithMessage).message === 'string'
)
}
function getErrorMessage(error: unknown): string {
if (isErrorWithMessage(error)) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return String(error)
}
async function hasCommits(repoPath: string, env: Record<string, string>): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { env, silent: true })
@@ -197,7 +175,7 @@ export async function initLocalRepo(
throw new Error(`Directory exists but is not a valid Git repository. Please provide either a Git repository path or a simple directory name to create a new empty repository.`)
}
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('No such file or directory')) {
if (getErrorMessage(error).includes('No such file or directory')) {
throw error
}
throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${getErrorMessage(error)}`)
@@ -393,12 +371,12 @@ export async function cloneRepo(
try {
await executeCommand(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
if (getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
if (branch && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
@@ -496,12 +474,12 @@ export async function cloneRepo(
await executeCommand(cloneCmd, { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
if (getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
if (branch && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
-13
View File
@@ -31,7 +31,6 @@ export interface FileDiffResponse {
additions: number
deletions: number
isBinary: boolean
truncated?: boolean
}
export interface GitDiffOptions {
@@ -49,15 +48,3 @@ export interface GitBranch {
behind?: number
isWorktree?: boolean
}
export interface CommitFile {
path: string
status: GitFileStatusType
oldPath?: string
additions: number
deletions: number
}
export interface CommitDetails extends GitCommit {
files: CommitFile[]
}
-4
View File
@@ -103,10 +103,6 @@ export function createGitEnv(credentials: GitCredential[]): Record<string, strin
return env
}
export function createGitHubGitEnv(gitToken: string): Record<string, string> {
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken, type: 'pat' }])
}
export function findGitHubCredential(credentials: GitCredential[]): GitCredential | null {
if (!credentials || credentials.length === 0) return null
+12
View File
@@ -0,0 +1,12 @@
export function compareVersions(v1: string, v2: string): number {
const parts1 = v1.replace(/^v/, '').split('.').map(Number)
const parts2 = v2.replace(/^v/, '').split('.').map(Number)
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] ?? 0
const p2 = parts2[i] ?? 0
if (p1 > p2) return 1
if (p1 < p2) return -1
}
return 0
}
-117
View File
@@ -299,121 +299,4 @@ describe('Repo Git Routes', () => {
expect(body).toHaveProperty('error')
})
})
describe('POST /:id/git/discard', () => {
it('should return 404 when repo does not exist', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
const response = await app.request('/999/git/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths: ['file1.ts'] }),
})
const body = await response.json()
expect(response.status).toBe(404)
expect(body).toHaveProperty('error', 'Repo not found')
})
it('should return 400 when paths is not an array', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
const response = await app.request('/1/git/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths: 'not-an-array' }),
})
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toHaveProperty('error', 'paths is required and must be an array')
})
it('should return 400 when paths is missing', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
const response = await app.request('/1/git/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toHaveProperty('error', 'paths is required and must be an array')
})
it('should return 500 when git operation fails', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
const response = await app.request('/1/git/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths: ['file1.ts'], staged: false }),
})
const body = await response.json()
expect(response.status).toBe(500)
expect(body).toHaveProperty('error')
})
})
describe('GET /:id/git/commit/:hash', () => {
it('should return 404 when repo does not exist', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
const response = await app.request('/999/git/commit/abc123')
expect(response.status).toBe(404)
const body = await response.json()
expect(body).toHaveProperty('error', 'Repo not found')
})
it('should return 400 when hash is missing', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
const response = await app.request('/1/git/commit/')
expect(response.status).toBeGreaterThanOrEqual(400)
})
it('should return 500 when git operation fails', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
const response = await app.request('/1/git/commit/abc123')
expect(response.status).toBe(500)
const body = await response.json()
expect(body).toHaveProperty('error')
})
})
describe('GET /:id/git/commit/:hash/diff', () => {
it('should return 404 when repo does not exist', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
const response = await app.request('/999/git/commit/abc123/diff?path=file.ts')
expect(response.status).toBe(404)
const body = await response.json()
expect(body).toHaveProperty('error', 'Repo not found')
})
it('should return 400 when hash is missing', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
const response = await app.request('/1/git/commit//diff?path=file.ts')
expect(response.status).toBeGreaterThanOrEqual(400)
})
it('should return 400 when path query parameter is missing', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
const response = await app.request('/1/git/commit/abc123/diff')
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toHaveProperty('error', 'path query parameter is required')
})
it('should return 500 when git operation fails', async () => {
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
const response = await app.request('/1/git/commit/abc123/diff?path=file.ts')
expect(response.status).toBe(500)
const body = await response.json()
expect(body).toHaveProperty('error')
})
})
})
@@ -29,7 +29,6 @@ vi.mock('../../../src/utils/git-auth', () => ({
resolveGitIdentity: vi.fn().mockResolvedValue(null),
createGitIdentityEnv: vi.fn().mockReturnValue({}),
createSilentGitEnv: vi.fn(),
filterGitCredentials: vi.fn().mockReturnValue([]),
}))
vi.mock('../../../src/utils/git-errors', () => ({
@@ -776,624 +775,4 @@ describe('GitService', () => {
expect(result).toBe("Switched to branch 'main'")
})
})
describe('discardChanges', () => {
it('discards staged changes using restore --staged --worktree', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('Changes discarded')
const result = await service.discardChanges(1, ['file.ts', 'dir/file2.ts'], true, database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'restore', '--staged', '--worktree', '--source', 'HEAD', '--', 'file.ts', 'dir/file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('Changes discarded')
})
it('discards unstaged tracked changes using checkout', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('status')) {
return Promise.resolve('M file.ts\n')
}
if (args.includes('checkout')) {
return Promise.resolve('Updated 1 path')
}
return Promise.resolve('')
})
const result = await service.discardChanges(1, ['file.ts'], false, database)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'status', '--porcelain', '-u', '--', 'file.ts'],
{ env: expect.any(Object) }
)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'checkout', '--', 'file.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('Updated 1 path')
})
it('removes unstaged untracked files using git clean', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('status')) {
return Promise.resolve('?? untracked.ts\n')
}
if (args.includes('clean')) {
return Promise.resolve('Removed untracked.ts')
}
return Promise.resolve('')
})
const result = await service.discardChanges(1, ['untracked.ts'], false, database)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'untracked.ts'],
{ env: expect.any(Object) }
)
expect(result).toContain('Removed untracked.ts')
})
it('handles mixed tracked and untracked files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('status')) {
return Promise.resolve('M modified.ts\n?? untracked.ts\n')
}
if (args.includes('checkout')) {
return Promise.resolve('Updated 1 path')
}
if (args.includes('clean')) {
return Promise.resolve('Removed untracked.ts')
}
return Promise.resolve('')
})
const result = await service.discardChanges(1, ['modified.ts', 'untracked.ts'], false, database)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'checkout', '--', 'modified.ts'],
{ env: expect.any(Object) }
)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'untracked.ts'],
{ env: expect.any(Object) }
)
expect(result).toContain('Updated 1 path')
expect(result).toContain('Removed untracked.ts')
})
it('returns early when no paths provided', async () => {
const result = await service.discardChanges(1, [], false, database)
expect(executeCommandMock).not.toHaveBeenCalled()
expect(result).toBe('')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.discardChanges(1, ['file.ts'], false, database)).rejects.toThrow('Repository not found')
})
it('logs and throws error on git command failure', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
const error = new Error('Permission denied')
executeCommandMock.mockImplementation((args) => {
if (args.includes('status')) {
return Promise.resolve('M file.ts\n')
}
if (args.includes('checkout')) {
return Promise.reject(error)
}
return Promise.resolve('')
})
await expect(service.discardChanges(1, ['file.ts'], false, database)).rejects.toThrow()
})
it('handles directories in untracked clean operation', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('status')) {
return Promise.resolve('?? dir/\n')
}
if (args.includes('clean')) {
return Promise.resolve('Removing dir/')
}
return Promise.resolve('')
})
const result = await service.discardChanges(1, ['dir/'], false, database)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'dir/'],
{ env: expect.any(Object) }
)
expect(result).toContain('Removing dir/')
})
})
describe('getCommitDetails', () => {
it('returns full commit details with files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Initial commit')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('A\tfile1.ts\nM\tfile2.ts\nD\tfile3.ts\n')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('10\t5\tfile1.ts\n20\t15\tfile2.ts\n0\t30\tfile3.ts\n')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result).not.toBeNull()
expect(result?.hash).toBe('abc123')
expect(result?.authorName).toBe('John Doe')
expect(result?.authorEmail).toBe('john@example.com')
expect(result?.date).toBe('1609459200')
expect(result?.message).toBe('Initial commit')
expect(result?.files).toHaveLength(3)
expect(result?.files[0]).toEqual({
path: 'file1.ts',
status: 'added',
additions: 10,
deletions: 5
})
expect(result?.files[1]).toEqual({
path: 'file2.ts',
status: 'modified',
additions: 20,
deletions: 15
})
expect(result?.files[2]).toEqual({
path: 'file3.ts',
status: 'deleted',
oldPath: undefined,
additions: 0,
deletions: 30
})
})
it('handles renamed files in commit details', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Rename file')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('R\told.ts\tnew.ts\n')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('0\t0\tnew.ts\n')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result?.files).toHaveLength(1)
expect(result?.files[0]).toEqual({
path: 'new.ts',
status: 'renamed',
oldPath: 'old.ts',
additions: 0,
deletions: 0
})
})
it('handles copied files in commit details', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Copy file')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('C\toriginal.ts\tcopy.ts\n')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('0\t0\tcopy.ts\n')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result?.files).toHaveLength(1)
expect(result?.files[0]).toEqual({
path: 'copy.ts',
status: 'copied',
oldPath: 'original.ts',
additions: 0,
deletions: 0
})
})
it('returns empty files array for empty commit', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Empty commit')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result?.files).toHaveLength(0)
})
it('returns null when commit hash not found', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.getCommitDetails(1, 'nonexistent', database)
expect(result).toBeNull()
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.getCommitDetails(1, 'abc123', database)).rejects.toThrow('Repository not found')
})
it('marks unpushed commits correctly', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Local commit')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('M\tfile.ts\n')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('1\t1\tfile.ts\n')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('abc123\n')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result?.unpushed).toBe(true)
})
it('handles commit message with pipes correctly', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockImplementation((args) => {
if (args.includes('log') && !args.includes('--not')) {
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Fix: merge|conflict|handling')
}
if (args.includes('show') && args.includes('--name-status')) {
return Promise.resolve('')
}
if (args.includes('show') && args.includes('--numstat')) {
return Promise.resolve('')
}
if (args.includes('--not') && args.includes('--remotes')) {
return Promise.resolve('')
}
return Promise.resolve('')
})
const result = await service.getCommitDetails(1, 'abc123', database)
expect(result?.message).toBe('Fix: merge|conflict|handling')
})
it('throws error on git command failure', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
const error = new Error('Git error')
executeCommandMock.mockRejectedValue(error)
await expect(service.getCommitDetails(1, 'abc123', database)).rejects.toThrow('Failed to get commit details')
})
})
describe('getCommitDiff', () => {
it('returns diff for specific file in commit', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
const diffOutput = `diff --git a/file.ts b/file.ts
index abc123..def456 100644
--- a/file.ts
+++ b/file.ts
@@ -1,3 +1,4 @@
+new line
existing line 1
existing line 2
existing line 3`
executeCommandMock.mockResolvedValue(diffOutput)
const result = await service.getCommitDiff(1, 'abc123', 'file.ts', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', expect.stringContaining('/path/to/repo'), 'show', '--format=', 'abc123', '--', 'file.ts'],
{ env: expect.any(Object) }
)
expect(result.path).toBe('file.ts')
expect(result.status).toBe('modified')
expect(result.diff).toContain('new line')
expect(result.additions).toBe(1)
expect(result.deletions).toBe(0)
expect(result.isBinary).toBe(false)
})
it('detects binary files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('Binary files a/image.png and b/image.png differ')
const result = await service.getCommitDiff(1, 'abc123', 'image.png', database)
expect(result.isBinary).toBe(true)
expect(result.diff).toContain('Binary files')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.getCommitDiff(1, 'abc123', 'file.ts', database)).rejects.toThrow('Repository not found')
})
it('handles deleted files in commit', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
const diffOutput = `diff --git a/deleted.ts b/deleted.ts
deleted file mode 100644
index abc123..0000000
--- a/deleted.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-line 1
-line 2
-line 3`
executeCommandMock.mockResolvedValue(diffOutput)
const result = await service.getCommitDiff(1, 'abc123', 'deleted.ts', database)
expect(result.deletions).toBe(3)
expect(result.additions).toBe(0)
})
it('throws error on git command failure', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
const error = new Error('Fatal error')
executeCommandMock.mockRejectedValue(error)
await expect(service.getCommitDiff(1, 'abc123', 'file.ts', database)).rejects.toThrow('Failed to get commit diff')
})
})
describe('parseDiffOutput', () => {
it('parses small diff and counts additions/deletions', () => {
const diffOutput = `diff --git a/file.ts b/file.ts
index abc123..def456 100644
--- a/file.ts
+++ b/file.ts
@@ -1,3 +1,4 @@
+added line
existing line 1
existing line 2
-removed line
existing line 3`
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result).toEqual({
path: 'file.ts',
status: 'modified',
diff: diffOutput,
additions: 1,
deletions: 1,
isBinary: false,
truncated: false
})
})
it('detects binary files correctly', () => {
const diffOutput = 'GIT binary patch\nliteral 1234\nzcmeAS@N?(olHy`uVBq!ia0vp0{ow;2j9U=!1jd#uLplI'
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'binary.bin')
expect(result.isBinary).toBe(true)
})
it('detects "Binary files" indicator', () => {
const diffOutput = 'Binary files a/image.png and b/image.png differ'
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'image.png')
expect(result.isBinary).toBe(true)
})
it('truncates diff when exceeding MAX_DIFF_SIZE (500KB)', () => {
const largeContent = '+' + 'x'.repeat(500 * 1024 + 1000)
const diffOutput = `diff --git a/large.ts b/large.ts\n${largeContent}`
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'large.ts')
expect(result.truncated).toBe(true)
expect(result.diff.length).toBe(500 * 1024 + '\n\n... (diff truncated due to size)'.length)
expect(result.diff).toContain('... (diff truncated due to size)')
})
it('does not truncate diff under MAX_DIFF_SIZE', () => {
const diffOutput = '+' + 'x'.repeat(100 * 1024)
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result.truncated).toBe(false)
expect(result.diff.length).toBeLessThan(500 * 1024)
})
it('handles empty diff', () => {
const diffOutput = ''
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result).toEqual({
path: 'file.ts',
status: 'modified',
diff: '',
additions: 0,
deletions: 0,
isBinary: false,
truncated: false
})
})
it('correctly counts multiple additions and deletions', () => {
const diffOutput = `diff --git a/file.ts b/file.ts
@@ -1,5 +1,7 @@
+added 1
context
+added 2
-removed 1
context
+added 3
-removed 2
-removed 3`
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result.additions).toBe(3)
expect(result.deletions).toBe(3)
})
it('ignores diff headers (+++/---) when counting', () => {
const diffOutput = `diff --git a/file.ts b/file.ts
--- a/file.ts
+++ b/file.ts
@@ -1,1 +1,2 @@
+added`
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result.additions).toBe(1)
expect(result.deletions).toBe(0)
})
it('handles different status types in parseDiffOutput', () => {
const diffOutput = '+new line'
const resultAdded = (service as any).parseDiffOutput(diffOutput, 'added', 'new.ts')
const resultDeleted = (service as any).parseDiffOutput(diffOutput, 'deleted', 'old.ts')
const resultRenamed = (service as any).parseDiffOutput(diffOutput, 'renamed', 'moved.ts')
expect(resultAdded.status).toBe('added')
expect(resultDeleted.status).toBe('deleted')
expect(resultRenamed.status).toBe('renamed')
})
it('handles diff with large change counts at truncation', () => {
const addedLines = '+' + 'x'.repeat(501 * 1024)
const diffOutput = `diff --git a/file.ts b/file.ts\n${addedLines}`
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
expect(result.truncated).toBe(true)
expect(result.diff).toContain('... (diff truncated due to size)')
})
})
})
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'bun:test'
import { describe, it, expect } from 'vitest'
import { parseGitError } from '../../src/utils/git-errors'
describe('parseGitError', () => {
+228
View File
@@ -0,0 +1,228 @@
# Memory Plugin (Optional)
`@opencode-manager/memory` is an **optional** OpenCode plugin that stores and recalls project knowledge across sessions using vector embeddings and semantic search.
!!! note "Not Required"
This plugin is entirely optional. OpenCode Manager works fully without it — install it only if you want persistent project knowledge and semantic search capabilities.
!!! tip "Works with Standalone OpenCode"
This plugin can also be used with standalone OpenCode installations outside of OpenCode Manager. Simply install the package and add it to your `opencode.json` plugins array.
## Installation
```bash
pnpm add @opencode-manager/memory
```
The local embedding model (`all-MiniLM-L6-v2`) is downloaded automatically via the `postinstall` script. For API-based embeddings (OpenAI or Voyage), skip the local model and set your provider and API key in the configuration instead.
Then register the plugin in your `opencode.json`:
```json
{
"plugin": ["@opencode-manager/memory"]
}
```
## Configuration
On first run, the plugin writes a default config to:
- `~/.local/share/opencode/memory/config.json`
- Falls back to `$XDG_DATA_HOME/opencode/memory/config.json`
The file is only created if it does not already exist.
```json
{
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2",
"dimensions": 384,
"baseUrl": "",
"apiKey": ""
},
"dataDir": "~/.local/share/opencode/memory",
"dedupThreshold": 0.25,
"logging": {
"enabled": false,
"file": "~/.local/share/opencode/memory/logs/memory.log"
},
"compaction": {
"customPrompt": true,
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
}
}
```
For API-based embeddings:
```json
{
"embedding": {
"provider": "openai",
"model": "text-embedding-3-small",
"apiKey": "sk-..."
}
}
```
### Embedding Providers
| Provider | Models | API Key Required |
|----------|--------|-----------------|
| `local` | `all-MiniLM-L6-v2` (384d) | No |
| `openai` | `text-embedding-3-small` (1536d), `text-embedding-3-large` (3072d), `text-embedding-ada-002` (1536d) | Yes |
| `voyage` | `voyage-code-3` (1024d), `voyage-2` (1536d) | Yes |
Set `baseUrl` to point at any OpenAI-compatible self-hosted service (vLLM, Ollama, LocalAI, LiteLLM, text-embeddings-inference). The URL is automatically normalized — providing `http://localhost:11434` appends `/v1/embeddings`.
### Options
| Key | Description | Default |
|-----|-------------|---------|
| `embedding.provider` | `local`, `openai`, or `voyage` | `local` |
| `embedding.model` | Model name | `all-MiniLM-L6-v2` |
| `embedding.dimensions` | Vector dimensions (auto-detected for known models) | — |
| `embedding.apiKey` | API key for OpenAI/Voyage | — |
| `embedding.baseUrl` | Custom endpoint for self-hosted services | — |
| `dataDir` | SQLite database directory | `~/.local/share/opencode/memory` |
| `dedupThreshold` | Similarity threshold for deduplication (0.05–0.40) | `0.25` |
| `logging.enabled` | Write logs to file | `false` |
| `logging.file` | Log file path (10MB limit, auto-rotated) | `…/logs/memory.log` |
| `compaction.customPrompt` | Use optimized compaction prompt | `true` |
| `compaction.inlinePlanning` | Include planning state in compaction context | `true` |
| `compaction.maxContextTokens` | Max tokens for injected memory context | `4000` |
| `compaction.snapshotToKV` | Save pre-compaction snapshot for recovery | `true` |
## Memory Model
### Scopes
| Scope | Description |
|-------|-------------|
| `convention` | Coding style rules, naming patterns, workflow preferences |
| `decision` | Architectural choices and their rationale |
| `context` | Project structure, key file locations, domain knowledge, known issues |
### Statuses
| Status | Description |
|--------|-------------|
| `active` | Available for injection and search |
| `archived` | Preserved but excluded from injection |
| `deleted` | Soft-deleted, not returned |
## Tools
The plugin registers seven tools that the AI agent can call directly:
| Tool | Description |
|------|-------------|
| `memory-read` | Search memories by semantic query or list by scope |
| `memory-write` | Store a new memory with a scope |
| `memory-edit` | Update the content or scope of an existing memory |
| `memory-delete` | Soft-delete a memory by ID |
| `memory-health` | Check plugin health or reindex all embeddings |
| `memory-planning-update` | Update session planning state (phases, objectives, progress) |
| `memory-planning-get` | Get the current planning state for a session |
### memory-read
```
query (optional) - Semantic search query
scope (optional) - Filter by convention | decision | context
limit (optional) - Max results (default: 10)
```
When `query` is provided, results are ranked by vector similarity. Without `query`, memories are listed in order.
### memory-write
```
content - The memory content to store
scope - convention | decision | context
```
Deduplication runs automatically — if a semantically similar memory already exists, the write is skipped and the existing ID is returned.
### memory-edit
```
id - Memory ID to update
content - New content
scope (optional) - New scope
```
### memory-delete
```
id - Memory ID to delete
```
### memory-health
```
action - check (default) | reindex
```
Use `check` to view embedding provider status, database health, memory count, and whether a reindex is needed. Use `reindex` to regenerate all embeddings after changing the model or dimensions.
!!! warning "Model Changes Require Reindex"
If you change `embedding.model` or `embedding.dimensions`, existing embeddings will have mismatched dimensions and search will fail. Run `memory-health` with `action: reindex` after any model change.
### memory-planning-update
```
sessionID - The session ID to update
objective (optional) - The main task/goal
current (optional) - Current phase or activity
next (optional) - What comes next
phases (optional) - Phase list with title, status, and optional notes
findings (optional) - Key discoveries (appended to existing)
errors (optional) - Errors to avoid (appended to existing)
```
Merges new fields with existing state. Findings and errors are deduplicated and appended rather than replaced.
### memory-planning-get
```
sessionID - The session ID to retrieve planning state for
```
Returns the current planning state including objective, phases, findings, and errors.
## Planning State
Planning state is separate from memories. It stores temporary session data — objectives, phase progress, findings, and errors — with a **7-day TTL**. After expiry, planning state is automatically cleaned up.
Use planning state to track multi-step tasks within a session. The plugin injects active planning state into compaction context so progress survives context window resets.
Memories, by contrast, are persisted indefinitely and retrieved via semantic search across all sessions.
## Automatic Extraction
After a session is compacted, the plugin automatically invokes the `ocm - Memory` agent to review the compaction summary and extract durable knowledge using `memory-write`. It checks for duplicates before writing by calling `memory-read` first.
Only persistent knowledge is stored — ephemeral task progress and session-specific notes are skipped.
## Compaction Awareness
When a session compaction is triggered, the plugin injects context into the compaction prompt:
- **Project memories** — up to 10 conventions and 10 decisions are included under a `## Project Memory` section so the AI's summary preserves them
- **Planning state** — active objective, current phase, next steps, and findings are prepended if present
- **Custom compaction prompt** — replaces the default prompt with one optimized for continuation context
A pre-compaction snapshot is also saved to key-value storage for recovery if needed.
## Deduplication
Before storing a new memory, the plugin:
1. Checks for exact content matches
2. Computes vector similarity against existing memories
3. Skips the write if similarity exceeds `dedupThreshold`
+10
View File
@@ -51,6 +51,16 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
[Learn more →](mcp.md)
### Memory Plugin (Optional)
- **Semantic Search** - Store and retrieve project knowledge using vector embeddings (requires plugin installation)
- **Memory Scopes** - Categorize as convention, decision, or context
- **Planning State** - Track objectives, phases, and progress across compactions
- **Automatic Extraction** - Durable knowledge extracted after session compaction
- **Compaction Awareness** - Injects project memories and planning state into compaction context
[Learn more →](memory.md)
### Text-to-Speech
- **Browser TTS** - Built-in Web Speech API support
+1
View File
@@ -34,6 +34,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
- **Push Notifications** - Get background alerts for agent events when app is closed
- **AI Configuration** - Configure models, providers, OAuth, and custom agents
- **MCP Servers** - Add local or remote MCP servers with OAuth support
- **Memory Plugin (Optional)** - Persistent project knowledge with semantic search and planning state
## Next Steps
+6
View File
@@ -6,6 +6,7 @@ import { Toaster } from 'sonner'
import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
import { SessionDetail } from './pages/SessionDetail'
import { Memories } from './pages/Memories'
import { Login } from './pages/Login'
import { Register } from './pages/Register'
import { Setup } from './pages/Setup'
@@ -130,6 +131,11 @@ const router = createBrowserRouter([
element: <SessionDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/memories',
element: <Memories />,
loader: protectedLoader,
},
],
},
])
+1 -35
View File
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { fetchWrapper, FetchError } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { GitStatusResponse, FileDiffResponse, GitCommit, CommitDetails } from '@/types/git'
import type { GitStatusResponse, FileDiffResponse, GitCommit } from '@/types/git'
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/status`)
@@ -22,12 +22,6 @@ export async function fetchFileDiff(repoId: number, path: string, includeStaged?
})
}
export async function fetchCommitFileDiff(repoId: number, commitHash: string, path: string): Promise<FileDiffResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${commitHash}/diff`, {
params: { path },
})
}
export async function fetchGitDiff(repoId: number, path: string): Promise<{ diff: string }> {
const data = await fetchWrapper<string>(`${API_BASE_URL}/api/repos/${repoId}/git/diff`, {
params: { path },
@@ -41,10 +35,6 @@ export async function fetchGitLog(repoId: number, limit?: number): Promise<{ com
})
}
export async function fetchCommitDetails(repoId: number, hash: string): Promise<CommitDetails> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${hash}`)
}
export async function gitFetch(repoId: number): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, {
method: 'POST',
@@ -89,14 +79,6 @@ export async function gitUnstageFiles(repoId: number, paths: string[]): Promise<
})
}
export async function gitDiscardFiles(repoId: number, paths: string[], staged: boolean): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/discard`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths, staged }),
})
}
export async function gitReset(repoId: number, commitHash: string): Promise<GitStatusResponse> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, {
method: 'POST',
@@ -122,14 +104,6 @@ export function useFileDiff(repoId: number | undefined, path: string | undefined
})
}
export function useCommitFileDiff(repoId: number | undefined, commitHash: string | undefined, path: string | undefined) {
return useQuery({
queryKey: ['commitFileDiff', repoId, commitHash, path],
queryFn: () => (repoId && commitHash && path) ? fetchCommitFileDiff(repoId, commitHash, path) : Promise.reject(new Error('Missing params')),
enabled: !!repoId && !!commitHash && !!path,
})
}
export function useGitLog(repoId: number | undefined, limit?: number) {
return useQuery({
queryKey: ['gitLog', repoId, limit],
@@ -138,14 +112,6 @@ export function useGitLog(repoId: number | undefined, limit?: number) {
})
}
export function useCommitDetails(repoId: number | undefined, hash: string | undefined) {
return useQuery({
queryKey: ['commitDetails', repoId, hash],
queryFn: () => (repoId && hash) ? fetchCommitDetails(repoId, hash) : Promise.reject(new Error('Missing params')),
enabled: !!repoId && !!hash,
})
}
function parseGitErrorMessage(message: string): string {
if (message.includes('no upstream') || message.includes('does not have any commits yet')) {
return 'No upstream branch configured. Push with --set-upstream or create commits first.'
+96
View File
@@ -0,0 +1,96 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig } from '@opencode-manager/shared/types'
export async function listMemories(filters?: {
projectId?: string
scope?: string
content?: string
limit?: number
offset?: number
}): Promise<{ memories: Memory[] }> {
const params = new URLSearchParams()
if (filters?.projectId) params.set('projectId', filters.projectId)
if (filters?.scope) params.set('scope', filters.scope)
if (filters?.content) params.set('content', filters.content)
if (filters?.limit) params.set('limit', String(filters.limit))
if (filters?.offset) params.set('offset', String(filters.offset))
const query = params.toString()
return fetchWrapper(`${API_BASE_URL}/api/memory${query ? `?${query}` : ''}`)
}
export async function createMemory(data: CreateMemoryRequest): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function getMemory(id: number): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/${id}`)
}
export async function updateMemory(id: number, data: UpdateMemoryRequest): Promise<{ memory: Memory }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function deleteMemory(id: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/memory/${id}`, {
method: 'DELETE',
})
}
export async function getProjectSummary(
repoId: number
): Promise<{ projectId: string | null; stats: MemoryStats; error?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/project-summary?repoId=${repoId}`)
}
export async function getPluginConfig(): Promise<{ config: PluginConfig }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/plugin-config`)
}
export async function updatePluginConfig(config: PluginConfig): Promise<{ success: boolean; config: PluginConfig }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/plugin-config`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
})
}
export interface ReindexResult {
success: boolean
message: string
total: number
embedded: number
failed: number
requiresRestart?: boolean
}
export async function reindexMemories(): Promise<ReindexResult> {
return fetchWrapper(`${API_BASE_URL}/api/memory/reindex`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
}
export interface TestEmbeddingResult {
success: boolean
error?: string
message?: string
dimensions?: number
}
export async function testEmbeddingConfig(): Promise<TestEmbeddingResult> {
return fetchWrapper(`${API_BASE_URL}/api/memory/test-embedding`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
}
+1 -5
View File
@@ -1,5 +1,5 @@
import type { Repo } from './types'
import { FetchError, fetchWrapper, fetchWrapperText, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
export async function createRepo(
@@ -51,10 +51,6 @@ export async function pullRepo(id: number): Promise<Repo> {
})
}
export async function getServerLogs(id: number): Promise<string> {
return fetchWrapperText(`${API_BASE_URL}/api/repos/${id}/server/logs`)
}
export async function switchRepoConfig(id: number, configName: string): Promise<Repo> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/config/switch`, {
method: 'POST',
+4
View File
@@ -210,6 +210,10 @@ export const settingsApi = {
getVersionInfo: async (): Promise<VersionInfo> => {
return fetchWrapper(`${API_BASE_URL}/api/health/version`)
},
getMemoryPluginStatus: async (): Promise<{ memoryPluginEnabled: boolean }> => {
return fetchWrapper(`${API_BASE_URL}/api/settings/memory-plugin-status`)
},
}
export interface VersionInfo {
+7 -6
View File
@@ -1,14 +1,15 @@
import { API_BASE_URL } from '@/config'
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
export function respondSSHHostKey(requestId: string, approved: boolean): Promise<{ success: boolean; error?: string }> {
interface SSHHostKeyResponse {
success: boolean
error?: string
}
export async function respondSSHHostKey(requestId: string, approved: boolean): Promise<SSHHostKeyResponse> {
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/respond`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ requestId, response: approved ? 'accept' : 'reject' }),
})
}
export function getSSHHostKeyStatus(): Promise<{ success: boolean; pendingCount?: number; error?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/status`)
}
+1 -7
View File
@@ -19,12 +19,6 @@ export interface CustomCommand {
promptTemplate: string
}
export interface CustomAgent {
name: string
description: string
config: Record<string, unknown>
}
export interface GitCredential {
name: string
host: string
@@ -55,13 +49,13 @@ export interface UserPreferences {
directShortcuts?: string[]
keyboardShortcuts: Record<string, string>
customCommands: CustomCommand[]
customAgents: CustomAgent[]
gitCredentials?: GitCredential[]
gitIdentity?: GitIdentity
tts?: TTSConfig
stt?: STTConfig
notifications?: NotificationPreferences
repoOrder?: number[]
memoryDedupThreshold?: number
}
export interface SettingsResponse {
@@ -1,4 +1,4 @@
import { useFileDiff, useCommitFileDiff } from "@/api/git";
import { useFileDiff } from "@/api/git";
import {
Loader2,
FileText,
@@ -10,7 +10,6 @@ import {
Minus,
ArrowLeft,
ExternalLink,
X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { CopyButton } from "@/components/ui/copy-button";
@@ -22,9 +21,7 @@ interface FileDiffViewProps {
repoId: number;
filePath: string;
includeStaged?: boolean;
commitHash?: string;
onBack?: () => void;
onClose?: () => void;
onOpenFile?: (path: string, lineNumber?: number) => void;
isMobile?: boolean;
}
@@ -139,7 +136,7 @@ function DiffLineComponent({
}) {
if (line.type === "header") {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono break-all border-b border-border/30">
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate border-b border-border/30">
{line.content}
</div>
);
@@ -147,7 +144,7 @@ function DiffLineComponent({
if (line.type === "hunk") {
return (
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono break-all border-b border-border/20">
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono border-b border-border/20">
{line.content}
</div>
);
@@ -173,7 +170,7 @@ function DiffLineComponent({
return (
<div
className={cn(
"flex font-mono text-sm border-l-2 transition-colors min-w-0",
"flex font-mono text-sm border-l-2 transition-colors",
bgClass,
line.type === "add" && "border-l-emerald-500",
line.type === "remove" && "border-l-rose-500",
@@ -204,7 +201,7 @@ function DiffLineComponent({
</div>
<pre
className={cn(
"flex-1 min-w-0 px-2 py-0.5 whitespace-pre-wrap break-words overflow-hidden",
"flex-1 px-2 py-0.5 whitespace-pre-wrap break-words",
textClass,
)}
>
@@ -218,15 +215,11 @@ export function FileDiffView({
repoId,
filePath,
includeStaged,
commitHash,
onBack,
onClose,
onOpenFile,
isMobile = false,
}: FileDiffViewProps) {
const workingDiff = useFileDiff(repoId, filePath, includeStaged);
const commitDiff = useCommitFileDiff(repoId, commitHash, filePath);
const { data: diffData, isLoading, error } = commitHash ? commitDiff : workingDiff;
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath, includeStaged);
const fileName = filePath.split("/").pop() || filePath;
const dirPath = filePath.includes("/")
@@ -266,7 +259,7 @@ export function FileDiffView({
const diffLines = diffData.diff ? parseDiff(diffData.diff) : [];
return (
<div className="flex flex-col h-full bg-background overflow-hidden">
<div className="flex flex-col h-full bg-background">
<div
className={cn(
"flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0",
@@ -338,20 +331,10 @@ export function FileDiffView({
className="flex-shrink-0"
/>
)}
{onClose && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 flex-shrink-0"
onClick={onClose}
>
<X className="w-4 h-4" />
</Button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
<div className="flex-1 overflow-y-auto min-h-0">
{diffData.isBinary ? (
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">Binary file - cannot display diff</p>
@@ -0,0 +1,147 @@
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useCreateMemory, useUpdateMemory } from '@/hooks/useMemories'
import type { Memory, CreateMemoryRequest, UpdateMemoryRequest } from '@opencode-manager/shared/types'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
const memorySchema = z.object({
content: z.string().min(1, 'Content is required').max(10000),
scope: z.enum(['convention', 'decision', 'context']),
})
type MemoryFormData = z.infer<typeof memorySchema>
interface MemoryFormDialogProps {
memory?: Memory
projectId?: string
open: boolean
onOpenChange: (open: boolean) => void
}
export function MemoryFormDialog({ memory, projectId, open, onOpenChange }: MemoryFormDialogProps) {
const createMutation = useCreateMemory()
const updateMutation = useUpdateMemory()
const {
register,
handleSubmit,
setValue,
watch,
reset,
formState: { errors },
} = useForm<MemoryFormData>({
resolver: zodResolver(memorySchema),
defaultValues: {
content: '',
scope: 'context',
},
})
const selectedScope = watch('scope')
useEffect(() => {
if (open) {
if (memory) {
reset({
content: memory.content,
scope: memory.scope,
})
} else {
reset({
content: '',
scope: 'context',
})
}
}
}, [open, memory, reset])
const onSubmit = async (data: MemoryFormData) => {
if (memory) {
const updateData: UpdateMemoryRequest = {
content: data.content,
scope: data.scope,
}
await updateMutation.mutateAsync({ id: memory.id, data: updateData })
} else if (projectId) {
const createData: CreateMemoryRequest = {
projectId,
content: data.content,
scope: data.scope,
}
await createMutation.mutateAsync(createData)
}
onOpenChange(false)
}
const isLoading = createMutation.isPending || updateMutation.isPending
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{memory ? 'Edit Memory' : 'Create Memory'}</DialogTitle>
<DialogDescription>
{memory
? 'Update the memory content and scope.'
: 'Add a new memory to store project knowledge.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="scope">Scope</Label>
<Select
value={selectedScope}
onValueChange={(value) => setValue('scope', value as MemoryFormData['scope'])}
>
<SelectTrigger>
<SelectValue placeholder="Select scope" />
</SelectTrigger>
<SelectContent>
<SelectItem value="convention">Convention</SelectItem>
<SelectItem value="decision">Decision</SelectItem>
<SelectItem value="context">Context</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
{...register('content')}
placeholder="Enter memory content..."
rows={5}
className="resize-none"
/>
{errors.content && (
<p className="text-sm text-destructive">{errors.content.message}</p>
)}
</div>
<DialogFooter className='flex gap-2 flex-wrap'>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : memory ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,146 @@
import { useState } from 'react'
import { useMemories, useDeleteMemory } from '@/hooks/useMemories'
import { useDebounce } from '@/hooks/useDebounce'
import type { Memory } from '@opencode-manager/shared/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Loader2, Trash2, Edit, Search } from 'lucide-react'
import { MemoryFormDialog } from './MemoryFormDialog'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
interface MemoryListProps {
projectId?: string
scope?: string
showFilters?: boolean
}
const scopeColors: Record<string, string> = {
convention: 'bg-blue-600/20 text-blue-400 border-blue-600/40',
decision: 'bg-green-600/20 text-green-400 border-green-600/40',
context: 'bg-purple-600/20 text-purple-400 border-purple-600/40',
}
export function MemoryList({ projectId, scope, showFilters = true }: MemoryListProps) {
const [filterScope, setFilterScope] = useState<string>(scope || 'all')
const [searchQuery, setSearchQuery] = useState<string>('')
const debouncedSearch = useDebounce(searchQuery, 300)
const [editMemory, setEditMemory] = useState<Memory | null>(null)
const [deleteMemoryId, setDeleteMemoryId] = useState<number | null>(null)
const filters = {
projectId,
scope: filterScope !== 'all' ? filterScope : undefined,
...(debouncedSearch ? { content: debouncedSearch } : undefined),
}
const { data: memories, isLoading } = useMemories(filters)
const deleteMutation = useDeleteMemory()
const handleDelete = () => {
if (deleteMemoryId !== null) {
deleteMutation.mutate(deleteMemoryId)
setDeleteMemoryId(null)
}
}
return (
<div className="space-y-4">
{showFilters && (
<div className="flex flex-wrap gap-2 items-center">
<Input
placeholder="Search memories..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-64"
/>
<Select value={filterScope} onValueChange={setFilterScope}>
<SelectTrigger className="w-36">
<SelectValue placeholder="Scope" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Scopes</SelectItem>
<SelectItem value="convention">Convention</SelectItem>
<SelectItem value="decision">Decision</SelectItem>
<SelectItem value="context">Context</SelectItem>
</SelectContent>
</Select>
</div>
)}
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : memories && memories.length === 0 ? (
<div className="text-center p-8 text-muted-foreground">
<Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No memories found</p>
</div>
) : (
<div className="space-y-2">
{memories?.map((memory) => (
<div
key={memory.id}
className="p-4 rounded-lg border border-border bg-card hover:bg-accent/50 transition-colors"
>
<div className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0">
<Badge className={`text-xs ${scopeColors[memory.scope]}`}>
{memory.scope}
</Badge>
{memory.filePath && (
<span className="text-xs text-muted-foreground truncate max-w-xs">
{memory.filePath}
</span>
)}
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setEditMemory(memory)}
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => setDeleteMemoryId(memory.id)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<p className="text-sm whitespace-pre-wrap break-words">{memory.content}</p>
<p className="text-xs text-muted-foreground mt-2">
Created: {new Date(memory.createdAt).toLocaleDateString()}
</p>
</div>
))}
</div>
)}
{editMemory && (
<MemoryFormDialog
memory={editMemory}
projectId={projectId}
open={!!editMemory}
onOpenChange={(open: boolean) => !open && setEditMemory(null)}
/>
)}
<DeleteDialog
open={deleteMemoryId !== null}
onOpenChange={(open: boolean) => !open && setDeleteMemoryId(null)}
onConfirm={handleDelete}
onCancel={() => setDeleteMemoryId(null)}
title="Delete Memory"
description="Are you sure you want to delete this memory? This action cannot be undone."
/>
</div>
)
}
@@ -1,52 +0,0 @@
import { X, Mic, MicOff } from 'lucide-react'
interface RecordingOverlayProps {
interimTranscript: string
onStop: () => void
onCancel: () => void
}
export function RecordingOverlay({
interimTranscript,
onStop,
onCancel
}: RecordingOverlayProps) {
return (
<div className="flex flex-col gap-3 py-2">
<div className="flex items-center justify-center h-12">
<div className="flex items-center gap-2 text-red-500">
<Mic className="w-5 h-5 animate-pulse" />
<span className="text-sm font-medium">Recording...</span>
</div>
</div>
<div className="min-h-[40px] px-3 py-2 bg-muted/50 rounded-lg">
{interimTranscript ? (
<p className="text-sm text-foreground">{interimTranscript}</p>
) : (
<p className="text-sm text-muted-foreground italic">Listening...</p>
)}
</div>
<div className="flex items-center justify-between gap-2">
<button
type="button"
onClick={onCancel}
className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
<X className="w-4 h-4" />
<span>Cancel</span>
</button>
<button
type="button"
onClick={onStop}
className="flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-white border border-red-500/60 shadow-md shadow-red-500/30 transition-all duration-200 active:scale-95"
>
<MicOff className="w-3 h-3" />
<span>Done</span>
</button>
</div>
</div>
)
}
@@ -0,0 +1,81 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { resetRepoPermissions } from "@/api/repos";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { showToast } from "@/lib/toast";
interface ResetPermissionsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoId: number;
repoDirectory?: string;
}
export function ResetPermissionsDialog({
open,
onOpenChange,
repoId,
repoDirectory,
}: ResetPermissionsDialogProps) {
const queryClient = useQueryClient();
const resetPermissionsMutation = useMutation({
mutationFn: () => resetRepoPermissions(repoId),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["opencode", "sessions", "http://localhost:5551", repoDirectory],
});
showToast.success("Permissions reset successfully");
onOpenChange(false);
},
onError: () => {
showToast.error("Failed to reset permissions");
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Permissions</DialogTitle>
<DialogDescription>
This will clear all "Allow Always" permissions for this repository.
You will be prompted again for permission when opencode needs to perform
actions like running commands or editing files.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={resetPermissionsMutation.isPending}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={() => resetPermissionsMutation.mutate()}
disabled={resetPermissionsMutation.isPending}
>
{resetPermissionsMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Resetting...
</>
) : (
"Reset Permissions"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -123,6 +123,8 @@ export function GeneralSettings() {
/>
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
@@ -0,0 +1,373 @@
import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Save, Loader2, Database, Brain, AlertCircle, RefreshCw, Play } from 'lucide-react'
import { getPluginConfig, updatePluginConfig, reindexMemories, testEmbeddingConfig } from '@/api/memory'
import { FetchError } from '@/api/fetchWrapper'
import { settingsApi } from '@/api/settings'
import type { PluginConfig, EmbeddingProviderType } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
const EMBEDDING_PROVIDERS: { value: EmbeddingProviderType; label: string }[] = [
{ value: 'local', label: 'Local (all-MiniLM-L6-v2)' },
{ value: 'openai', label: 'OpenAI' },
{ value: 'voyage', label: 'Voyage AI' },
]
const DEFAULT_CONFIGS: Record<EmbeddingProviderType, { model: string; dimensions: number }> = {
local: { model: 'all-MiniLM-L6-v2', dimensions: 384 },
openai: { model: 'text-embedding-3-small', dimensions: 1536 },
voyage: { model: 'voyage-3', dimensions: 1024 },
}
interface MemoryPluginConfigProps {
memoryPluginEnabled: boolean
onToggle: (enabled: boolean) => void
}
export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPluginConfigProps) {
const queryClient = useQueryClient()
const [expanded, setExpanded] = useState(false)
const [showApiKey, setShowApiKey] = useState(false)
const { data, isLoading, error } = useQuery({
queryKey: ['memory-plugin-config'],
queryFn: getPluginConfig,
staleTime: 60000,
enabled: memoryPluginEnabled && expanded,
})
const config = data?.config
const [localConfig, setLocalConfig] = useState<PluginConfig | null>(null)
useEffect(() => {
if (config && !localConfig) {
setLocalConfig(config)
}
}, [config, localConfig])
const handleProviderChange = (provider: EmbeddingProviderType) => {
if (!localConfig && !config) return
const defaults = DEFAULT_CONFIGS[provider]
setLocalConfig({
embedding: {
provider,
model: defaults.model,
dimensions: defaults.dimensions,
},
dedupThreshold: config?.dedupThreshold ?? 0.25,
})
}
const updateMutation = useMutation({
mutationFn: updatePluginConfig,
onSuccess: (data) => {
showToast.success('Memory plugin configuration saved')
queryClient.setQueryData(['memory-plugin-config'], { config: data.config })
},
onError: () => {
showToast.error('Failed to save configuration')
},
})
const reindexMutation = useMutation({
mutationFn: reindexMemories,
onSuccess: (data) => {
if (data.requiresRestart) {
showToast.success(data.message)
} else {
showToast.success(`Reindex complete: ${data.embedded}/${data.total} memories embedded`)
}
},
onError: () => {
showToast.error('Failed to reindex memories')
},
})
const testMutation = useMutation({
mutationFn: testEmbeddingConfig,
onSuccess: (data) => {
showToast.success(data.message || 'Configuration test passed')
},
onError: (error) => {
const message = error instanceof FetchError ? error.message : 'Failed to test configuration'
showToast.error(message)
},
})
const handleReindex = () => {
reindexMutation.mutate()
}
const handleTest = async () => {
if (isDirty && localConfig) {
await updateMutation.mutateAsync(localConfig)
}
testMutation.mutate()
}
const handleSave = async () => {
if (!localConfig) return
updateMutation.mutate(localConfig, {
onSuccess: async () => {
showToast.loading('Restarting OpenCode server...', { id: 'memory-restart' })
try {
await settingsApi.restartOpenCodeServer()
showToast.success('Configuration saved and server restarted', { id: 'memory-restart' })
} catch {
showToast.error('Failed to restart server', { id: 'memory-restart' })
}
},
})
}
const handleFieldChange = (field: keyof PluginConfig['embedding'], value: string | number | undefined) => {
if (!localConfig && !config) return
setLocalConfig({
...(localConfig ?? config!),
embedding: {
...(localConfig?.embedding ?? config!.embedding),
[field]: value === '' ? undefined : value,
},
})
}
const displayConfig = localConfig ?? config
const isApiProvider = displayConfig?.embedding.provider !== 'local'
const isDirty = localConfig !== null && JSON.stringify(localConfig) !== JSON.stringify(config)
return (
<Card className="mt-4 border-transparent">
<CardHeader className="py-3">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-4">
<button
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-2 p-1 hover:opacity-80 transition-opacity"
>
{expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
<Brain className="h-4 w-4 text-blue-500" />
<CardTitle className="text-sm">Memory Plugin</CardTitle>
</button>
<Switch
checked={memoryPluginEnabled}
onCheckedChange={onToggle}
/>
</div>
</div>
<CardDescription className="text-xs">
Configure embedding, deduplication, and storage options
</CardDescription>
</CardHeader>
{memoryPluginEnabled && expanded && (
<CardContent className="space-y-6 pt-0">
{isLoading && (
<div className="flex items-center gap-2 p-4">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-muted-foreground">Loading configuration...</span>
</div>
)}
{error && (
<div className="flex items-center gap-2 p-4 text-destructive">
<AlertCircle className="h-4 w-4" />
<span>Failed to load plugin configuration</span>
</div>
)}
{config && !isLoading && !error && displayConfig && (
<>
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<span className="text-sm font-medium">Embedding</span>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="provider">Provider</Label>
<select
id="provider"
className="flex h-10 w-full rounded-md bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
value={displayConfig.embedding.provider}
onChange={(e) => handleProviderChange(e.target.value as EmbeddingProviderType)}
>
{EMBEDDING_PROVIDERS.map((p) => (
<option key={p.value} value={p.value}>
{p.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<Label htmlFor="model">Model</Label>
<Input
id="model"
value={displayConfig.embedding.model}
onChange={(e) => handleFieldChange('model', e.target.value)}
placeholder="Model name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dimensions">Dimensions</Label>
<Input
id="dimensions"
type="number"
value={displayConfig.embedding.dimensions ?? ''}
onChange={(e) => handleFieldChange('dimensions', e.target.value ? parseInt(e.target.value, 10) : undefined)}
placeholder="384"
/>
</div>
{isApiProvider && (
<>
<div className="space-y-2">
<Label htmlFor="apiKey">API Key</Label>
<div className="relative">
<Input
id="apiKey"
type={showApiKey ? 'text' : 'password'}
value={displayConfig.embedding.apiKey ?? ''}
onChange={(e) => handleFieldChange('apiKey', e.target.value)}
placeholder="Enter API key"
className="pr-10"
/>
<button
type="button"
onClick={() => setShowApiKey(!showApiKey)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showApiKey ? <span className="text-xs">Hide</span> : <span className="text-xs">Show</span>}
</button>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="baseUrl">Base URL (optional)</Label>
<Input
id="baseUrl"
value={displayConfig.embedding.baseUrl ?? ''}
onChange={(e) => handleFieldChange('baseUrl', e.target.value)}
placeholder="https://api.openai.com"
/>
<p className="text-xs text-muted-foreground">
Root URL without path — /v1/embeddings is appended automatically
</p>
</div>
</>
)}
</div>
</div>
<div className="space-y-4 border-t pt-4">
<div className="flex items-center gap-2 mb-3">
<Database className="h-4 w-4 text-green-500" />
<span className="text-sm font-medium">Storage</span>
</div>
<div className="space-y-2">
<Label htmlFor="dedupThreshold">Deduplication Threshold</Label>
<div className="flex items-center gap-4">
<input
id="dedupThreshold"
type="range"
min="0"
max="0.4"
step="0.05"
value={displayConfig.dedupThreshold ?? 0.25}
onChange={(e) => {
setLocalConfig({
...displayConfig,
dedupThreshold: parseFloat(e.target.value),
})
}}
className="flex-1"
/>
<span className="text-sm text-muted-foreground w-12">
{(displayConfig.dedupThreshold ?? 0.25).toFixed(2)}
</span>
</div>
<p className="text-xs text-muted-foreground">
Lower values = more aggressive deduplication (0.0 - 0.4)
</p>
</div>
</div>
{displayConfig.dataDir && (
<div className="space-y-2">
<Label>Data Directory</Label>
<Input value={displayConfig.dataDir} disabled className="text-muted-foreground text-xs" />
</div>
)}
<div className="space-y-4 border-t pt-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<RefreshCw className="h-4 w-4 text-purple-500" />
<span className="text-sm font-medium">Reindex</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleReindex}
disabled={reindexMutation.isPending}
>
{reindexMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<RefreshCw className="h-4 w-4 mr-1" />
)}
Reindex
</Button>
</div>
<p className="text-xs text-muted-foreground">
Regenerate embeddings for all memories. Use when changing embedding model or if embeddings are missing.
</p>
</div>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<AlertCircle className="h-3 w-3" />
<span>Server will restart automatically after saving</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={handleTest}
disabled={testMutation.isPending}
>
{testMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Play className="h-4 w-4 mr-1" />
)}
Test
</Button>
<Button
size="sm"
onClick={handleSave}
disabled={!isDirty || updateMutation.isPending}
>
{updateMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Save className="h-4 w-4 mr-1" />
)}
Save
</Button>
</div>
</div>
</>
)}
</CardContent>
)}
</Card>
)
}
@@ -1,4 +1,5 @@
import { useState, useEffect, useRef } from 'react'
import { cn } from '@/lib/utils'
import { Loader2, Plus, Trash2, Edit, StarOff, Download, RotateCcw, FileText, ArrowUpCircle, History } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -13,6 +14,7 @@ import { AgentsEditor } from './AgentsEditor'
import { AgentsMdEditor } from './AgentsMdEditor'
import { McpManager } from './McpManager'
import { VersionSelectDialog } from './VersionSelectDialog'
import { MemoryPluginConfig } from './MemoryPluginConfig'
import { settingsApi } from '@/api/settings'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useServerHealth } from '@/hooks/useServerHealth'
@@ -183,7 +185,8 @@ export function OpenCodeConfigManager() {
}
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
if (restartServer || agentsChanged) {
const pluginsChanged = JSON.stringify(previousContent?.plugin) !== JSON.stringify(newContent.plugin)
if (restartServer || agentsChanged || pluginsChanged) {
showToast.loading('Reloading server...', { id: 'update-restart' })
try {
await reloadConfigMutation.mutateAsync()
@@ -328,10 +331,10 @@ export function OpenCodeConfigManager() {
return (
<div className="space-y-6 overflow-y-auto">
{health && (
<Card className={isUnhealthy ? 'border-destructive' : ''}>
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
<CardContent className="p-3">
<div className="flex flex-col sm:flex-row sm:items-center items-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center sm:justify-start">
<div className="flex flex-col sm:flex-row sm:items-center items-center justify-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center ">
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
<p className="font-medium text-sm sm:text-base">
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
@@ -418,8 +421,32 @@ export function OpenCodeConfigManager() {
</div>
</CardContent>
</Card>
)}
<CreateConfigDialog
)}
<MemoryPluginConfig
memoryPluginEnabled={configs.find(c => c.isDefault)?.content?.plugin?.includes('@opencode-manager/memory') ?? false}
onToggle={async (enabled) => {
const defaultConfig = configs.find(c => c.isDefault)
if (!defaultConfig) return
const currentPlugins = defaultConfig.content?.plugin ?? []
const memoryPlugin = '@opencode-manager/memory'
const newPlugins = enabled
? currentPlugins.includes(memoryPlugin)
? currentPlugins
: [...currentPlugins, memoryPlugin]
: currentPlugins.filter(p => p !== memoryPlugin)
await updateConfigContent(defaultConfig.name, {
...defaultConfig.content,
plugin: newPlugins.length > 0 ? newPlugins : undefined
}, true)
queryClient.invalidateQueries({ queryKey: ['memory-plugin-status'] })
}}
/>
<CreateConfigDialog
isOpen={isCreateDialogOpen}
onOpenChange={setIsCreateDialogOpen}
onCreate={createConfig}
@@ -446,7 +473,7 @@ export function OpenCodeConfigManager() {
return 0
})
.map((config) => (
<Card key={config.id} className={config.isDefault ? 'border-green-500' : ''}>
<Card key={config.id} className={cn('border-transparent', config.isDefault && 'border-green-500')}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 flex-wrap">
@@ -4,28 +4,23 @@ import { useGit } from '@/hooks/useGit'
import { GitFlatFileList } from './GitFlatFileList'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { DiscardDialog } from '@/components/ui/discard-dialog'
import { Loader2, GitCommit, FileText, AlertCircle } from 'lucide-react'
interface ChangesTabProps {
repoId: number
onFileSelect: (path: string, staged: boolean) => void
onClearFileSelection?: () => void
selectedFile?: {path: string, staged: boolean}
isMobile: boolean
onError?: (error: unknown) => void
}
export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selectedFile, isMobile, onError }: ChangesTabProps) {
export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onError }: ChangesTabProps) {
const { data: status, isLoading, error } = useGitStatus(repoId)
const git = useGit(repoId, onError)
const [commitMessage, setCommitMessage] = useState('')
const [discardDialogOpen, setDiscardDialogOpen] = useState(false)
const [discardPaths, setDiscardPaths] = useState<string[]>([])
const [discardStaged, setDiscardStaged] = useState(false)
const stagedFiles = status?.files.filter(f => f.staged) || []
const unstagedFiles = status?.files.filter(f => !f.staged) || []
const canCommit = commitMessage.trim() && stagedFiles.length > 0 && !git.commit.isPending
@@ -38,23 +33,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
git.unstageFiles.mutate(paths)
}
const handleDiscard = (paths: string[], staged: boolean) => {
setDiscardPaths(paths)
setDiscardStaged(staged)
setDiscardDialogOpen(true)
}
const confirmDiscard = () => {
git.discardFiles.mutate({ paths: discardPaths, staged: discardStaged })
setDiscardDialogOpen(false)
setDiscardPaths([])
}
const cancelDiscard = () => {
setDiscardDialogOpen(false)
setDiscardPaths([])
}
const handleCommit = () => {
git.commit.mutate({ message: commitMessage.trim() })
setCommitMessage('')
@@ -82,13 +60,83 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
if (isMobile && selectedFile) {
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden">
<FileDiffView
repoId={repoId}
filePath={selectedFile.path}
includeStaged={selectedFile.staged}
onBack={onClearFileSelection}
/>
<div className="flex flex-col h-full">
<Tabs defaultValue="files" className="flex flex-col h-full">
<TabsList className="flex-shrink-0">
<TabsTrigger value="files">Files ({stagedFiles.length + unstagedFiles.length})</TabsTrigger>
<TabsTrigger value="diff">{selectedFile.path.split('/').pop() || selectedFile.path}</TabsTrigger>
</TabsList>
<TabsContent value="files" className="flex-1 overflow-hidden mt-0">
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{status.hasChanges ? (
<>
{stagedFiles.length > 0 && (
<GitFlatFileList
files={stagedFiles}
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
selectedFile={selectedFile?.path}
/>
)}
{unstagedFiles.length > 0 && (
<GitFlatFileList
files={unstagedFiles}
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
selectedFile={selectedFile?.path}
/>
)}
</>
) : (
<div className="text-center py-12 text-muted-foreground">
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No uncommitted changes</p>
</div>
)}
</div>
{status.hasChanges && (
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] md:text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<Button
onClick={handleCommit}
disabled={!canCommit}
className="w-full h-9"
>
{git.commit.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<GitCommit className="w-4 h-4 mr-2" />
)}
Commit {stagedFiles.length > 0 && `(${stagedFiles.length} staged)`}
</Button>
<p className="text-[10px] text-muted-foreground text-center">
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}+Enter to commit
</p>
</div>
)}
</div>
</TabsContent>
<TabsContent value="diff" className="flex-1 overflow-hidden mt-0">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</TabsContent>
</Tabs>
</div>
)
} else {
@@ -103,7 +151,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
onDiscard={handleDiscard}
selectedFile={selectedFile?.path}
/>
)}
@@ -114,7 +161,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
onDiscard={handleDiscard}
selectedFile={selectedFile?.path}
/>
)}
@@ -157,15 +203,6 @@ export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selecte
</p>
</div>
)}
<DiscardDialog
open={discardDialogOpen}
onOpenChange={setDiscardDialogOpen}
onConfirm={confirmDiscard}
onCancel={cancelDiscard}
fileCount={discardPaths.length}
isDiscarding={git.discardFiles.isPending}
/>
</div>
)
}
@@ -1,102 +0,0 @@
import { useCommitDetails } from '@/api/git'
import { Loader2, GitCommit, ArrowLeft } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { GitFlatFileList } from './GitFlatFileList'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
interface CommitDetailViewProps {
repoId: number
commitHash: string
onBack: () => void
onFileSelect: (path: string) => void
selectedFile?: string
}
export function CommitDetailView({ repoId, commitHash, onBack, onFileSelect, selectedFile }: CommitDetailViewProps) {
const { data: commit, isLoading, error } = useCommitDetails(repoId, commitHash)
if (isLoading) {
return (
<div className="flex items-center justify-center h-full py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)
}
if (error || !commit) {
return (
<div className="text-center py-12 text-muted-foreground">
<GitCommit className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load commit details</p>
<p className="text-xs mt-1">{error?.message}</p>
<Button variant="outline" size="sm" onClick={onBack} className="mt-4">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to commits
</Button>
</div>
)
}
const commitFiles = commit.files.map(f => ({
path: f.path,
status: f.status,
staged: false,
oldPath: f.oldPath,
additions: f.additions,
deletions: f.deletions
}))
const totalAdditions = commit.files.reduce((sum, f) => sum + (f.additions || 0), 0)
const totalDeletions = commit.files.reduce((sum, f) => sum + (f.deletions || 0), 0)
if (selectedFile) {
return (
<div className="flex flex-col h-full min-h-0 overflow-hidden">
<FileDiffView
repoId={repoId}
filePath={selectedFile}
includeStaged={false}
commitHash={commitHash}
onBack={() => onFileSelect('')}
/>
</div>
)
}
return (
<div className="flex flex-col h-full">
<div className="px-3 py-3 border-b border-border flex-shrink-0 space-y-2">
<div className="flex items-start gap-2">
<Button
variant="ghost"
size="sm"
onClick={onBack}
className="h-7 w-7 p-0 flex-shrink-0 mt-0.5"
>
<ArrowLeft className="w-4 h-4" />
</Button>
<p className="text-sm font-medium leading-snug">{commit.message}</p>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground pl-9">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{new Date(parseInt(commit.date, 10) * 1000).toLocaleDateString()}</span>
</div>
</div>
<div className="flex-1 overflow-y-auto px-1 pt-1">
<GitFlatFileList
files={commitFiles}
staged={false}
onSelect={(path) => onFileSelect(path)}
selectedFile={selectedFile}
readOnly={true}
totalAdditions={totalAdditions}
totalDeletions={totalDeletions}
/>
</div>
</div>
)
}
@@ -59,41 +59,34 @@ export function CommitsTab({ repoId, onSelectCommit }: CommitsTabProps) {
}
return (
<div className="flex flex-col h-full overflow-x-hidden">
<div className="flex-1 overflow-y-auto overflow-x-hidden">
{data.commits.map((commit) => (
<button
key={commit.hash}
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
onClick={() => onSelectCommit?.(commit.hash)}
>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
<GitCommit className="w-4 h-4 text-muted-foreground" />
<div className="flex flex-col h-full overflow-y-auto">
{data.commits.map((commit) => (
<button
key={commit.hash}
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
onClick={() => onSelectCommit?.(commit.hash)}
>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
<GitCommit className="w-4 h-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{commit.message}</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
Local
</span>
)}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium line-clamp-2">{commit.message}</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground overflow-hidden">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
Local
</span>
)}
{!commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.pushed)}>
Remote
</span>
)}
</div>
</div>
</button>
))}
</div>
</div>
</button>
))}
</div>
)
}
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button'
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot, RotateCcw } from 'lucide-react'
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { GitFileStatus } from '@/types/git'
import { GIT_STATUS_COLORS, GIT_UI_COLORS } from '@/lib/git-status-styles'
@@ -10,7 +10,6 @@ interface GitFlatFileItemProps {
onSelect: (path: string, staged: boolean) => void
onStage?: (path: string) => void
onUnstage?: (path: string) => void
onDiscard?: (path: string, staged: boolean) => void
}
const statusIcons = {
@@ -22,7 +21,7 @@ const statusIcons = {
copied: FilePlus,
}
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage, onDiscard }: GitFlatFileItemProps) {
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage }: GitFlatFileItemProps) {
const StatusIcon = statusIcons[file.status] || FileText
const statusColor = GIT_STATUS_COLORS[file.status] || 'text-muted-foreground'
@@ -38,13 +37,6 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
}
}
const handleDiscard = (e: React.MouseEvent) => {
e.stopPropagation()
if (onDiscard) {
onDiscard(file.path, file.staged)
}
}
return (
<div
className={cn(
@@ -67,41 +59,18 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
staged
</span>
)}
{(file.additions !== undefined || file.deletions !== undefined) && (
<div className="flex items-center gap-1 text-xs flex-shrink-0">
{file.additions !== undefined && file.additions > 0 && (
<span className="text-green-500">+{file.additions}</span>
)}
{file.deletions !== undefined && file.deletions > 0 && (
<span className="text-red-500">-{file.deletions}</span>
)}
</div>
)}
{(onStage || onUnstage) && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleAction}
>
{file.staged ? (
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
) : (
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
)}
</Button>
)}
{onDiscard && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleDiscard}
title="Discard changes"
>
<RotateCcw className="w-3 h-3 text-rose-500" />
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleAction}
>
{file.staged ? (
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
) : (
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
)}
</Button>
</div>
)
}
@@ -12,11 +12,7 @@ interface GitFlatFileListProps {
onSelect: (path: string, staged: boolean) => void
onStage?: (paths: string[]) => void
onUnstage?: (paths: string[]) => void
onDiscard?: (paths: string[], staged: boolean) => void
selectedFile?: string
readOnly?: boolean
totalAdditions?: number
totalDeletions?: number
}
interface GroupedFiles {
@@ -32,11 +28,7 @@ export function GitFlatFileList({
onSelect,
onStage,
onUnstage,
onDiscard,
selectedFile,
readOnly = false,
totalAdditions,
totalDeletions,
}: GitFlatFileListProps) {
const [collapsedGroups, setCollapsedGroups] = useState<Set<GitFileStatusType>>(new Set())
@@ -91,13 +83,6 @@ export function GitFlatFileList({
}
}
const handleDiscardAll = (e: React.MouseEvent) => {
e.stopPropagation()
if (onDiscard) {
onDiscard(filteredFiles.map(f => f.path), staged)
}
}
if (filteredFiles.length === 0) {
return null
}
@@ -108,44 +93,24 @@ export function GitFlatFileList({
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{staged ? 'Staged Changes' : 'Changes'} ({filteredFiles.length})
</span>
{(totalAdditions !== undefined && totalAdditions > 0 || totalDeletions !== undefined && totalDeletions > 0) && (
<div className="flex items-center gap-1 text-xs">
{totalAdditions !== undefined && totalAdditions > 0 && <span className="text-green-500">+{totalAdditions}</span>}
{totalDeletions !== undefined && totalDeletions > 0 && <span className="text-red-500">-{totalDeletions}</span>}
</div>
)}
{!readOnly && (
<div className="flex items-center gap-1">
{onDiscard && (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs text-rose-500 hover:text-rose-600"
onClick={handleDiscardAll}
>
Discard All
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={staged ? handleUnstageAll : handleStageAll}
>
{staged ? (
<>
<Minus className="w-3 h-3 mr-1" />
Unstage All
</>
) : (
<>
<Plus className="w-3 h-3 mr-1" />
Stage All
</>
)}
</Button>
</div>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={staged ? handleUnstageAll : handleStageAll}
>
{staged ? (
<>
<Minus className="w-3 h-3 mr-1" />
Unstage All
</>
) : (
<>
<Plus className="w-3 h-3 mr-1" />
Stage All
</>
)}
</Button>
</div>
{groupedFiles.map(({ status, files: groupFiles }) => {
@@ -178,9 +143,8 @@ export function GitFlatFileList({
file={file}
isSelected={selectedFile === file.path}
onSelect={onSelect}
onStage={readOnly ? undefined : handleStageFile}
onUnstage={readOnly ? undefined : handleUnstageFile}
onDiscard={readOnly ? undefined : onDiscard ? ((path: string, staged: boolean) => onDiscard([path], staged)) : undefined}
onStage={handleStageFile}
onUnstage={handleUnstageFile}
/>
))}
</div>
@@ -6,7 +6,6 @@ import { useGit } from '@/hooks/useGit'
import { ChangesTab } from './ChangesTab'
import { CommitsTab } from './CommitsTab'
import { BranchesTab } from './BranchesTab'
import { CommitDetailView } from './CommitDetailView'
import { GitErrorBanner } from './GitErrorBanner'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { Button } from '@/components/ui/button'
@@ -38,7 +37,6 @@ interface SourceControlPanelProps {
}
type Tab = 'changes' | 'commits' | 'branches'
type View = 'default' | 'commit-detail'
export function SourceControlPanel({
repoId,
@@ -51,9 +49,6 @@ export function SourceControlPanel({
}: SourceControlPanelProps) {
const [activeTab, setActiveTab] = useState<Tab>('changes')
const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>()
const [currentView, setCurrentView] = useState<View>('default')
const [selectedCommit, setSelectedCommit] = useState<string | undefined>()
const [selectedCommitFile, setSelectedCommitFile] = useState<string | undefined>()
const [gitError, setGitError] = useState<{ summary: string; detail?: string } | null>(null)
const { data: status } = useGitStatus(repoId)
const isMobile = useMobile()
@@ -77,18 +72,6 @@ export function SourceControlPanel({
}
}
const handleSelectCommit = (hash: string) => {
setSelectedCommit(hash)
setCurrentView('commit-detail')
}
const handleBackToCommits = () => {
setSelectedCommit(undefined)
setSelectedCommitFile(undefined)
setCurrentView('default')
setActiveTab('commits')
}
const tabs: { id: Tab; label: string; icon: React.ElementType }[] = [
{ id: 'changes', label: 'Changes', icon: FileCode },
{ id: 'commits', label: 'Commits', icon: History },
@@ -99,7 +82,7 @@ export function SourceControlPanel({
const stagedCount = status?.files.filter(f => f.staged).length || 0
const content = (
<div className="flex flex-col h-full gap-0">
<div className="flex flex-col h-full">
<div className="flex items-center justify-between px-3 py-2 border-b border-border flex-shrink-0">
<div className="flex items-center gap-2">
<div className="flex items-center gap-2">
@@ -171,79 +154,69 @@ export function SourceControlPanel({
<GitErrorBanner error={gitError} onDismiss={() => setGitError(null)} />
)}
{!((currentView === 'commit-detail' && selectedCommitFile) || (isMobile && selectedFile && activeTab === 'changes')) && (
<div className="flex border-b border-border flex-shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon
return (
<button
key={tab.id}
className={cn(
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === tab.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
)}
onClick={() => setActiveTab(tab.id)}
>
<Icon className="w-4 h-4" />
<span>{tab.label}</span>
{tab.id === 'changes' && changesCount > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
</span>
)}
</button>
)
})}
</div>
)}
<div className="flex border-b border-border flex-shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon
return (
<button
key={tab.id}
className={cn(
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === tab.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
)}
onClick={() => setActiveTab(tab.id)}
>
<Icon className="w-4 h-4" />
<span>{tab.label}</span>
{tab.id === 'changes' && changesCount > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
</span>
)}
</button>
)
})}
</div>
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col gap-0' : 'flex')}>
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col' : 'flex')}>
<div className={cn(
'overflow-hidden min-h-0 h-full flex flex-col',
isMobile
? 'flex-1'
: currentView === 'commit-detail'
? 'flex-1'
: selectedFile
? 'w-[35%] border-r border-border'
: 'flex-1'
'overflow-hidden',
isMobile ? 'flex-1' : selectedFile ? 'w-[35%] border-r border-border' : 'flex-1'
)}>
{activeTab === 'changes' && (
<ChangesTab
repoId={repoId}
onFileSelect={(path, staged) => setSelectedFile({ path, staged })}
onClearFileSelection={() => setSelectedFile(undefined)}
selectedFile={selectedFile}
isMobile={isMobile}
onError={handleGitError}
/>
)}
{activeTab === 'commits' && currentView === 'default' && (
<CommitsTab repoId={repoId} onSelectCommit={handleSelectCommit} />
{activeTab === 'commits' && (
<CommitsTab repoId={repoId} />
)}
{activeTab === 'branches' && currentView === 'default' && (
{activeTab === 'branches' && (
<BranchesTab repoId={repoId} currentBranch={currentBranch} repoUrl={repoUrl} isRepoWorktree={isRepoWorktree} />
)}
{currentView === 'commit-detail' && selectedCommit && (
<div className="flex flex-1 min-h-0 overflow-hidden flex-col">
<CommitDetailView
repoId={repoId}
commitHash={selectedCommit}
onBack={handleBackToCommits}
onFileSelect={setSelectedCommitFile}
selectedFile={selectedCommitFile}
/>
</div>
)}
</div>
{selectedFile && !isMobile && currentView === 'default' && (
{selectedFile && !isMobile && (
<div className="flex-1 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
<span className="text-sm font-medium truncate">{selectedFile.path}</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => setSelectedFile(undefined)}
>
<X className="w-4 h-4" />
</Button>
</div>
<div className="flex-1 overflow-auto">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} onClose={() => setSelectedFile(undefined)} />
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</div>
</div>
)}
@@ -257,12 +230,12 @@ export function SourceControlPanel({
mobileFullscreen
hideCloseButton={isMobile}
className={cn(
'p-0 flex flex-col bg-card border-border gap-0',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0'
'p-0 flex flex-col bg-card border-border',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh]'
)}
>
<DialogHeader className={cn(
'px-4 py-2 border-b border-border flex-shrink-0',
'px-4 py-3 border-b border-border flex-shrink-0',
isMobile && 'relative'
)}>
<DialogTitle className="flex items-center gap-2">
@@ -280,7 +253,7 @@ export function SourceControlPanel({
</Button>
)}
</DialogHeader>
<div className="flex-1 overflow-hidden pb-0">
<div className="flex-1 overflow-hidden">
{content}
</div>
</DialogContent>
@@ -1,59 +0,0 @@
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle } from 'lucide-react'
interface DiscardDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
fileCount: number
isDiscarding?: boolean
}
export function DiscardDialog({
open,
onOpenChange,
onConfirm,
onCancel,
fileCount,
isDiscarding = false
}: DiscardDialogProps) {
const itemText = fileCount === 1 ? '1 file' : `${fileCount} files`
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className='max-w-[90%] sm:max-w-sm'>
<DialogHeader>
<DialogTitle>Discard Changes</DialogTitle>
<DialogDescription>
Are you sure you want to discard changes to {itemText}? This action cannot be undone.
</DialogDescription>
</DialogHeader>
<Alert className="overflow-hidden">
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
<AlertDescription>
This will permanently delete your uncommitted changes to {itemText}. If these changes exist in the staging area, they will also be removed.
</AlertDescription>
</Alert>
<DialogFooter className='gap-2'>
<Button variant="outline" onClick={onCancel} disabled={isDiscarding}>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isDiscarding}
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
>
{isDiscarding && 'Discarding...'}
{!isDiscarding && 'Discard'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,85 +0,0 @@
import { memo, type ReactNode } from 'react'
import { X, VolumeX, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
type FloatingActionVariant = 'clear' | 'stop-audio' | 'custom'
interface FloatingActionButtonProps {
variant: FloatingActionVariant
onClick: () => void
visible: boolean
loading?: boolean
icon?: ReactNode
label?: string
position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'
className?: string
}
const variantConfig: Record<FloatingActionVariant, { icon: ReactNode; label: string; colors: string }> = {
'clear': {
icon: <X className="w-5 h-5" />,
label: 'Clear',
colors: 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 border-2 border-red-500/60 hover:border-red-400 shadow-lg shadow-red-500/30 hover:shadow-red-500/50 ring-2 ring-red-500/20 hover:ring-red-500/40 text-destructive-foreground'
},
'stop-audio': {
icon: <VolumeX className="w-5 h-5" />,
label: 'Stop Audio',
colors: 'bg-gradient-to-br from-red-700 to-red-800 hover:from-red-600 hover:to-red-700 border-2 border-red-600/80 hover:border-red-500 shadow-2xl shadow-red-600/40 hover:shadow-red-600/60 ring-2 ring-red-600/30 hover:ring-red-600/50 animate-[pulse_2s_cubic-bezier(0.4,0,0.6,1)_infinite] text-destructive-foreground',
},
'custom': {
icon: null,
label: '',
colors: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground border-border'
}
}
const positionClasses: Record<NonNullable<FloatingActionButtonProps['position']>, string> = {
'top-right': 'top-4 right-4',
'top-left': 'top-4 left-4',
'bottom-right': 'bottom-4 right-4',
'bottom-left': 'bottom-4 left-4'
}
export const FloatingActionButton = memo(function FloatingActionButton({
variant,
onClick,
visible,
loading = false,
icon,
label,
position = 'top-right',
className
}: FloatingActionButtonProps) {
const config = variantConfig[variant]
const displayIcon = icon ?? config.icon
const displayLabel = label ?? config.label
if (!visible) return null
return (
<button
onClick={onClick}
disabled={loading}
className={cn(
'fixed z-50 flex items-center gap-2 px-4 py-2 rounded-xl backdrop-blur-md transition-all duration-200',
'min-w-[48px] min-h-[48px]',
'active:scale-95 hover:scale-105',
'transition-transform',
config.colors,
positionClasses[position],
loading && 'opacity-70 cursor-not-allowed grayscale',
className
)}
aria-label={displayLabel}
>
{loading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
displayIcon
)}
{displayLabel && (
<span className="text-sm font-medium hidden sm:inline">{displayLabel}</span>
)}
</button>
)
})
+12
View File
@@ -0,0 +1,12 @@
import { useState, useEffect } from 'react'
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(timer)
}, [value, delay])
return debouncedValue
}
+1 -13
View File
@@ -1,5 +1,5 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage } from '@/api/git'
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage } from '@/api/git'
import { createBranch, switchBranch } from '@/api/repos'
import { showToast } from '@/lib/toast'
@@ -94,17 +94,6 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
onError: handleError,
})
const discardFilesMutation = useMutation({
mutationFn: ({ paths, staged }: { paths: string[]; staged: boolean }) => {
if (!repoId) throw new Error('No repo ID')
return gitDiscardFiles(repoId, paths, staged)
},
onSuccess: () => {
invalidateCache()
},
onError: handleError,
})
const log = useMutation({
mutationFn: ({ limit }: { limit?: number }) => {
if (!repoId) throw new Error('No repo ID')
@@ -164,7 +153,6 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
commit,
stageFiles: stageFilesMutation,
unstageFiles: unstageFilesMutation,
discardFiles: discardFilesMutation,
log,
diff,
createBranch: createBranchMutation,
+94
View File
@@ -0,0 +1,94 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
listMemories,
createMemory,
getMemory,
updateMemory,
deleteMemory,
getProjectSummary,
} from '@/api/memory'
import type { CreateMemoryRequest, UpdateMemoryRequest } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
export function useMemories(filters?: {
projectId?: string
scope?: string
content?: string
limit?: number
offset?: number
}) {
return useQuery({
queryKey: ['memories', filters?.projectId, filters?.scope, filters?.content],
queryFn: () => listMemories(filters).then(r => r.memories),
enabled: !!filters?.projectId,
})
}
export function useMemory(id: number | undefined) {
return useQuery({
queryKey: ['memory', id],
queryFn: () => {
if (id === undefined) throw new Error('Memory ID required')
return getMemory(id).then(r => r.memory)
},
enabled: id !== undefined,
})
}
export function useCreateMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: CreateMemoryRequest) => createMemory(data).then(r => r.memory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('Memory created')
},
onError: (error) => {
showToast.error(`Failed to create memory: ${error}`)
},
})
}
export function useUpdateMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ id, data }: { id: number; data: UpdateMemoryRequest }) =>
updateMemory(id, data).then(r => r.memory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
showToast.success('Memory updated')
},
onError: (error) => {
showToast.error(`Failed to update memory: ${error}`)
},
})
}
export function useDeleteMemory() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: number) => deleteMemory(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['memories'] })
showToast.success('Memory deleted')
},
onError: (error) => {
showToast.error(`Failed to delete memory: ${error}`)
},
})
}
export function useProjectSummary(repoId: number | undefined) {
return useQuery({
queryKey: ['projectSummary', repoId],
queryFn: () => {
if (repoId === undefined) throw new Error('Repo ID required')
return getProjectSummary(repoId)
},
enabled: repoId !== undefined,
})
}
@@ -1,70 +0,0 @@
import { useState, useEffect, useCallback } from 'react'
interface PassphraseRequest {
type: 'passphrase-request'
credentialName: string
host: string
}
interface UsePassphraseHandlerProps {
enabled?: boolean
onSubmit?: (passphrase: string) => void
}
export function usePassphraseHandler({ enabled = true, onSubmit }: UsePassphraseHandlerProps = {}) {
const [isOpen, setIsOpen] = useState(false)
const [credentialName, setCredentialName] = useState<string>('SSH key')
const [host, setHost] = useState<string>('')
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!enabled) return
const handlePassphraseRequest = (event: MessageEvent) => {
const data = event.data as PassphraseRequest
if (data.type === 'passphrase-request') {
setCredentialName(data.credentialName)
setHost(data.host)
setIsOpen(true)
setError(null)
}
}
window.addEventListener('message', handlePassphraseRequest)
return () => {
window.removeEventListener('message', handlePassphraseRequest)
}
}, [enabled])
const handleSubmitPassphrase = useCallback((passphrase: string) => {
try {
onSubmit?.(passphrase)
setIsOpen(false)
setError(null)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to submit passphrase')
}
}, [onSubmit])
const sendPassphraseResponse = useCallback((passphrase: string) => {
window.postMessage({
type: 'passphrase-response',
passphrase
}, '*')
}, [])
const handleSubmit = useCallback((passphrase: string) => {
sendPassphraseResponse(passphrase)
handleSubmitPassphrase(passphrase)
}, [sendPassphraseResponse, handleSubmitPassphrase])
return {
isOpen,
credentialName,
host,
error,
onSubmit: handleSubmit,
onOpenChange: setIsOpen
}
}
-22
View File
@@ -1,22 +0,0 @@
import { useState, useEffect } from 'react'
export function useStandalone() {
const [isStandalone, setIsStandalone] = useState(false)
useEffect(() => {
const checkStandalone = () => {
const isIOSStandalone = ('standalone' in window.navigator) && (window.navigator as Navigator & { standalone: boolean }).standalone
const isDisplayModeStandalone = window.matchMedia('(display-mode: standalone)').matches
setIsStandalone(isIOSStandalone || isDisplayModeStandalone)
}
checkStandalone()
const mediaQuery = window.matchMedia('(display-mode: standalone)')
mediaQuery.addEventListener('change', checkStandalone)
return () => mediaQuery.removeEventListener('change', checkStandalone)
}, [])
return isStandalone
}
+1 -2
View File
@@ -15,8 +15,7 @@ export const GIT_UI_COLORS = {
stage: 'text-emerald-600 dark:text-emerald-400',
unstage: 'text-rose-600 dark:text-rose-400',
stagedBadge: 'bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400',
unpushed: 'bg-blue-500/10 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400',
pushed: 'bg-purple-500/10 text-purple-600 dark:bg-purple-500/20 dark:text-purple-400',
unpushed: 'bg-amber-500/10 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400',
} as const
export const GIT_STATUS_LABELS = {
-123
View File
@@ -1,123 +0,0 @@
export interface McpServerTemplate {
id: string
name: string
description: string
type: 'local' | 'remote'
command?: string[]
url?: string
environment?: Record<string, string>
docsUrl?: string
}
export const MCP_SERVER_TEMPLATES: McpServerTemplate[] = [
{
id: 'filesystem',
name: 'Filesystem',
description: 'Access and manipulate local files and directories',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-filesystem', '/tmp'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem',
},
{
id: 'git',
name: 'Git',
description: 'Interact with Git repositories',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-git', '--repository', '.'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/git',
},
{
id: 'sqlite',
name: 'SQLite',
description: 'Query and manage SQLite databases',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-sqlite', '--db-path', './data.db'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite',
},
{
id: 'postgres',
name: 'PostgreSQL',
description: 'Connect to PostgreSQL databases',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-postgres'],
environment: {
POSTGRES_CONNECTION_STRING: 'postgresql://user:password@localhost:5432/dbname',
},
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/postgres',
},
{
id: 'brave-search',
name: 'Brave Search',
description: 'Web search using Brave Search API',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-brave-search'],
environment: {
BRAVE_API_KEY: 'your-brave-api-key-here',
},
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search',
},
{
id: 'github',
name: 'GitHub',
description: 'Interact with GitHub repositories and issues',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-github'],
environment: {
GITHUB_PERSONAL_ACCESS_TOKEN: 'your-github-token-here',
},
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/github',
},
{
id: 'slack',
name: 'Slack',
description: 'Read and send messages to Slack channels',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-slack'],
environment: {
SLACK_BOT_TOKEN: 'xoxb-your-slack-bot-token',
},
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/slack',
},
{
id: 'puppeteer',
name: 'Puppeteer',
description: 'Web automation and scraping with Puppeteer',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-puppeteer'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer',
},
{
id: 'fetch',
name: 'Fetch',
description: 'Make HTTP requests to web APIs',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-fetch'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/fetch',
},
{
id: 'memory',
name: 'Memory',
description: 'Persistent memory storage for conversations',
type: 'local',
command: ['npx', '@modelcontextprotocol/server-memory'],
docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/memory',
},
{
id: 'custom-local',
name: 'Custom Local Server',
description: 'Run a custom MCP server locally',
type: 'local',
command: ['node', '/path/to/your/server.js'],
},
{
id: 'custom-remote',
name: 'Custom Remote Server',
description: 'Connect to a remote MCP server via HTTP',
type: 'remote',
url: 'http://localhost:3000/mcp',
},
]
export function getMcpServerTemplate(id: string): McpServerTemplate | undefined {
return MCP_SERVER_TEMPLATES.find((t) => t.id === id)
}
-369
View File
@@ -1,369 +0,0 @@
export interface ProviderTemplate {
id: string
name: string
description: string
npm: string
options?: {
baseURL?: string
[key: string]: unknown
}
models?: Record<string, {
name: string
limit?: {
context: number
output: number
}
}>
requiresApiKey: boolean
docsUrl?: string
}
export const PROVIDER_TEMPLATES: ProviderTemplate[] = [
{
id: 'opencode',
name: 'OpenCode Zen',
description: 'Tested models from OpenCode (Recommended)',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.opencode.ai/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/zen/',
models: {
'qwen3-coder-480b': {
name: 'Qwen 3 Coder 480B',
},
},
},
{
id: 'anthropic',
name: 'Anthropic',
description: 'Claude models from Anthropic',
npm: '@ai-sdk/anthropic',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#anthropic',
models: {
'claude-3-5-sonnet-20241022': {
name: 'Claude 3.5 Sonnet',
limit: { context: 200000, output: 8192 },
},
'claude-3-5-haiku-20241022': {
name: 'Claude 3.5 Haiku',
limit: { context: 200000, output: 8192 },
},
},
},
{
id: 'openai',
name: 'OpenAI',
description: 'GPT models from OpenAI',
npm: '@ai-sdk/openai',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#openai',
models: {
'gpt-4o': {
name: 'GPT-4o',
limit: { context: 128000, output: 4096 },
},
'gpt-4o-mini': {
name: 'GPT-4o Mini',
limit: { context: 128000, output: 16384 },
},
},
},
{
id: 'google',
name: 'Google',
description: 'Gemini models from Google',
npm: '@ai-sdk/google',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#google-vertex-ai',
models: {
'gemini-1.5-pro': {
name: 'Gemini 1.5 Pro',
limit: { context: 2000000, output: 8192 },
},
'gemini-1.5-flash': {
name: 'Gemini 1.5 Flash',
limit: { context: 1000000, output: 8192 },
},
},
},
{
id: 'deepseek',
name: 'DeepSeek',
description: 'DeepSeek models including DeepSeek Reasoner',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.deepseek.com/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#deepseek',
models: {
'deepseek-reasoner': {
name: 'DeepSeek Reasoner',
},
'deepseek-chat': {
name: 'DeepSeek Chat',
},
},
},
{
id: 'groq',
name: 'Groq',
description: 'Fast inference with Groq',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.groq.com/openai/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#groq',
models: {
'llama-3.1-70b-versatile': {
name: 'Llama 3.1 70B',
},
},
},
{
id: 'openrouter',
name: 'OpenRouter',
description: 'Access multiple models through OpenRouter',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://openrouter.ai/api/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#openrouter',
models: {
'anthropic/claude-3.5-sonnet': {
name: 'Claude 3.5 Sonnet (via OpenRouter)',
},
},
},
{
id: 'cerebras',
name: 'Cerebras',
description: 'Fast inference including Qwen 3 Coder',
npm: '@ai-sdk/cerebras',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#cerebras',
models: {
'qwen3-480b': {
name: 'Qwen 3 Coder 480B',
},
},
},
{
id: 'fireworks',
name: 'Fireworks AI',
description: 'Fast model inference including Kimi K2',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.fireworks.ai/inference/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#fireworks-ai',
models: {
'kimi-k2-instruct': {
name: 'Kimi K2 Instruct',
},
},
},
{
id: 'together',
name: 'Together AI',
description: 'Access to multiple open source models',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.together.xyz/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#together-ai',
models: {
'kimi-k2-instruct': {
name: 'Kimi K2 Instruct',
},
},
},
{
id: 'deepinfra',
name: 'Deep Infra',
description: 'Serverless inference for open models',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.deepinfra.com/v1/openai',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#deep-infra',
},
{
id: 'baseten',
name: 'Baseten',
description: 'Serverless GPU inference',
npm: '@ai-sdk/openai-compatible',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#baseten',
},
{
id: 'huggingface',
name: 'Hugging Face',
description: 'Access to 17+ inference providers',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api-inference.huggingface.co/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#hugging-face',
models: {
'kimi-k2-instruct': {
name: 'Kimi K2 Instruct',
},
'glm-4.6': {
name: 'GLM 4.6',
},
},
},
{
id: 'moonshot',
name: 'Moonshot AI',
description: 'Kimi K2 models from Moonshot AI',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.moonshot.cn/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#moonshot-ai',
models: {
'kimi-k2': {
name: 'Kimi K2',
},
},
},
{
id: 'cortecs',
name: 'Cortecs',
description: 'AI inference platform',
npm: '@ai-sdk/openai-compatible',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#cortecs',
models: {
'kimi-k2-instruct': {
name: 'Kimi K2 Instruct',
},
},
},
{
id: 'zai',
name: 'Z.AI',
description: 'GLM models from Z.AI',
npm: '@ai-sdk/openai-compatible',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#zai',
models: {
'glm-4.5': {
name: 'GLM 4.5',
},
},
},
{
id: 'ovhcloud',
name: 'OVHcloud AI Endpoints',
description: 'European cloud AI inference',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://endpoints.ai.cloud.ovh.net/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#ovhcloud-ai-endpoints',
models: {
'gpt-oss-120b': {
name: 'GPT OSS 120B',
},
},
},
{
id: 'xai',
name: 'xAI',
description: 'Grok models from xAI',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.x.ai/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#xai',
models: {
'grok-beta': {
name: 'Grok Beta',
},
},
},
{
id: 'zenmux',
name: 'ZenMux',
description: 'Multi-provider AI gateway',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.zenmux.ai/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#zenmux',
},
{
id: 'github-copilot',
name: 'GitHub Copilot',
description: 'Use your GitHub Copilot subscription',
npm: '@ai-sdk/openai-compatible',
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#github-copilot',
},
{
id: 'ollama',
name: 'Ollama (Local)',
description: 'Run models locally with Ollama',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'http://localhost:11434/v1',
},
requiresApiKey: false,
docsUrl: 'https://opencode.ai/docs/providers/#ollama',
models: {
'llama3.2': {
name: 'Llama 3.2',
},
'qwen2.5-coder': {
name: 'Qwen 2.5 Coder',
},
},
},
{
id: 'lmstudio',
name: 'LM Studio (Local)',
description: 'Run models locally with LM Studio',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'http://127.0.0.1:1234/v1',
},
requiresApiKey: false,
docsUrl: 'https://opencode.ai/docs/providers/#lm-studio',
models: {
'google/gemma-3n-e4b': {
name: 'Gemma 3n-e4b',
},
},
},
{
id: 'custom-openai-compatible',
name: 'Custom OpenAI-Compatible',
description: 'Any OpenAI-compatible API endpoint',
npm: '@ai-sdk/openai-compatible',
options: {
baseURL: 'https://api.example.com/v1',
},
requiresApiKey: true,
docsUrl: 'https://opencode.ai/docs/providers/#custom-provider',
},
]
export function getProviderTemplate(id: string): ProviderTemplate | undefined {
return PROVIDER_TEMPLATES.find((t) => t.id === id)
}
+115
View File
@@ -0,0 +1,115 @@
import { useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useProjectSummary } from '@/hooks/useMemories'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { Loader2, Plus, Brain } from 'lucide-react'
import { getRepoDisplayName } from '@/lib/utils'
import { MemoryList } from '@/components/memory/MemoryList'
import { MemoryFormDialog } from '@/components/memory/MemoryFormDialog'
export function Memories() {
const { id } = useParams<{ id: string }>()
const repoId = id ? Number(id) : undefined
const [createOpen, setCreateOpen] = useState(false)
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined,
})
const { data: projectSummary, isLoading: projectSummaryLoading } = useProjectSummary(repoId)
const projectId = projectSummary?.projectId ?? null
const stats = projectSummary?.stats ?? null
if (repoLoading || projectSummaryLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!repo) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">Repository not found</p>
</div>
)
}
if (!projectId) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">No project ID found - the repository may not have any commits yet</p>
</div>
)
}
const scopeLabels: Record<string, string> = {
convention: 'Convention',
decision: 'Decision',
context: 'Context',
}
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<div className="min-w-0 flex-1 flex justify-center ml-2">
<Header.Title className="hidden sm:flex ">
Memory: {getRepoDisplayName(repo.repoUrl, repo.localPath)}
</Header.Title>
<Header.Title className="sm:hidden truncate">
{getRepoDisplayName(repo.repoUrl, repo.localPath)}
</Header.Title>
</div>
<Header.Actions>
<Button onClick={() => setCreateOpen(true)} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
New Memory
</Button>
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden">
<Plus className="w-4 h-4" />
</Button>
</Header.Actions>
</Header>
<div className="flex-1 overflow-auto p-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
{stats && (
<Card className="mb-6 hidden sm:block">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-3">
<Brain className="w-4 h-4 text-blue-500" />
<span className="font-medium">Total Memories: {stats.total}</span>
</div>
{Object.keys(stats.byScope).length > 0 && (
<div className="flex flex-wrap gap-2">
{Object.entries(stats.byScope).map(([scope, count]) => (
<Badge key={scope} variant="outline" className="text-sm">
{scopeLabels[scope] || scope}: {count}
</Badge>
))}
</div>
)}
</CardContent>
</Card>
)}
<MemoryList projectId={projectId} showFilters={true} />
</div>
<MemoryFormDialog
projectId={projectId}
open={createOpen}
onOpenChange={setCreateOpen}
/>
</div>
)
}
+33 -59
View File
@@ -1,7 +1,8 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { getRepo, resetRepoPermissions } from "@/api/repos";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getRepo } from "@/api/repos";
import { settingsApi } from "@/api/settings";
import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Header } from "@/components/ui/header";
@@ -15,20 +16,11 @@ import { useSwipeBack } from "@/hooks/useMobile";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Plug, FolderOpen, Plus, GitBranch, Loader2, GitCommitHorizontal, ShieldOff } from "lucide-react";
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2 } from "lucide-react";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { showToast } from "@/lib/toast";
import { invalidateConfigCaches } from "@/lib/queryInvalidation";
import { getRepoDisplayName } from "@/lib/utils";
export function RepoDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
@@ -59,6 +51,12 @@ export function RepoDetail() {
enabled: !!repoId,
});
const { data: memoryPluginStatus } = useQuery({
queryKey: ["memory-plugin-status"],
queryFn: () => settingsApi.getMemoryPluginStatus(),
staleTime: 60000,
});
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = repo?.fullPath;
@@ -67,18 +65,6 @@ export function RepoDetail() {
const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory);
const resetPermissionsMutation = useMutation({
mutationFn: () => resetRepoPermissions(repoId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, repoDirectory] });
showToast.success("Permissions reset successfully");
setResetPermissionsOpen(false);
},
onError: () => {
showToast.error("Failed to reset permissions");
},
});
const handleCreateSession = async (options?: {
agentSlug?: string;
promptSlug?: string;
@@ -187,7 +173,23 @@ export function RepoDetail() {
<ShieldOff className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Reset Permissions</span>
</Button>
{memoryPluginStatus?.memoryPluginEnabled && (
<Button
variant="outline"
onClick={() => navigate(`/repos/${repoId}/memories`)}
size="sm"
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<Brain className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Memory</span>
</Button>
)}
<Header.MobileDropdown>
{memoryPluginStatus?.memoryPluginEnabled && (
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
<Brain className="w-4 h-4 mr-2" /> Memory
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
@@ -261,40 +263,12 @@ export function RepoDetail() {
/>
)}
<Dialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Permissions</DialogTitle>
<DialogDescription>
This will clear all "Allow Always" permissions for this repository.
You will be prompted again for permission when opencode needs to perform actions like running commands or editing files.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setResetPermissionsOpen(false)}
disabled={resetPermissionsMutation.isPending}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={() => resetPermissionsMutation.mutate()}
disabled={resetPermissionsMutation.isPending}
>
{resetPermissionsMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Resetting...
</>
) : (
"Reset Permissions"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ResetPermissionsDialog
open={resetPermissionsOpen}
onOpenChange={setResetPermissionsOpen}
repoId={repoId}
repoDirectory={repoDirectory}
/>
</div>
);
}
+36 -3
View File
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
import { getRepo } from "@/api/repos";
import { MessageThread } from "@/components/message/MessageThread";
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
import { X, VolumeX, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal } from "lucide-react";
import { X, VolumeX, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal, Brain, ShieldOff } from "lucide-react";
import { ModelSelectDialog } from "@/components/model/ModelSelectDialog";
import { Header } from "@/components/ui/header";
import { SessionList } from "@/components/session/SessionList";
@@ -32,6 +32,7 @@ import type { MessageWithParts } from "@/api/types";
import { showToast } from "@/lib/toast";
import { getRepoDisplayName } from "@/lib/utils";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { createOpenCodeClient } from "@/api/opencode";
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
import { useQuestions } from "@/contexts/EventContext";
@@ -60,6 +61,7 @@ export function SessionDetail() {
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
const [sourceControlOpen, setSourceControlOpen] = useState(false);
const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false);
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
const [showScrollButton, setShowScrollButton] = useState(false);
const [hasPromptContent, setHasPromptContent] = useState(false);
@@ -387,6 +389,24 @@ export function SessionDetail() {
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Source</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={() => navigate(`/repos/${repoId}/memories`)}
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<Brain className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Memory</span>
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setResetPermissionsOpen(true)}
className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<ShieldOff className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Reset Permissions</span>
</Button>
<Button
variant="outline"
size="sm"
@@ -397,15 +417,21 @@ export function SessionDetail() {
<span className="hidden sm:inline">Settings</span>
</Button>
<Header.MobileDropdown>
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
<Brain className="w-4 h-4 mr-2" /> Memory
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
<FolderOpen className="w-4 h-4 mr-2" /> Files
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
</DropdownMenuItem>
</Header.MobileDropdown>
</Header.Actions>
</Header>
@@ -545,6 +571,13 @@ export function SessionDetail() {
currentBranch={repo.currentBranch || repo.branch || "main"}
repoName={getRepoDisplayName(repo.repoUrl, repo.localPath)}
/>
<ResetPermissionsDialog
open={resetPermissionsOpen}
onOpenChange={setResetPermissionsOpen}
repoId={repoId}
repoDirectory={repoDirectory}
/>
</div>
);
}
-6
View File
@@ -45,10 +45,4 @@ export const useSessionTodosForSession = (sessionID: string | undefined): Todo[]
sessionID ? state.todos.get(sessionID) : undefined
)
return todos || []
}
export const useHasSessionTodos = (sessionID: string | undefined): boolean => {
return useSessionTodos((state) =>
sessionID ? (state.todos.get(sessionID)?.length ?? 0) > 0 : false
)
}
-14
View File
@@ -5,8 +5,6 @@ export interface GitFileStatus {
status: GitFileStatusType
staged: boolean
oldPath?: string
additions?: number
deletions?: number
}
export interface GitCommit {
@@ -18,18 +16,6 @@ export interface GitCommit {
unpushed?: boolean
}
export interface CommitFile {
path: string
status: GitFileStatusType
oldPath?: string
additions: number
deletions: number
}
export interface CommitDetails extends GitCommit {
files: CommitFile[]
}
export interface GitStatusResponse {
branch: string
ahead: number
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opencode-manager",
"version": "0.9.03",
"version": "0.9.04",
"private": false,
"type": "module",
"packageManager": "pnpm@10.28.1",
+3
View File
@@ -0,0 +1,3 @@
dist/
node_modules/
*.tsbuildinfo
+7
View File
@@ -0,0 +1,7 @@
src/
test/
tsconfig.json
tsconfig.build.json
*.tsbuildinfo
node_modules/
.gitignore
+110
View File
@@ -0,0 +1,110 @@
# @opencode-manager/memory
Memory management plugin for OpenCode that enables semantic search and persistent storage of project knowledge.
## Features
- **Semantic Memory Search** - Store and retrieve project memories using vector embeddings
- **Multiple Memory Scopes** - Categorize memories as convention, decision, or context
- **Automatic Deduplication** - Prevents duplicate memories from being stored
- **Session Context** - Tracks session state and injects relevant memories during compaction
## Tools
| Tool | Description |
|------|-------------|
| `memory-read` | Search and retrieve project memories with semantic search |
| `memory-write` | Store a new project memory |
| `memory-edit` | Update an existing project memory |
| `memory-delete` | Delete a project memory by ID |
| `memory-health` | Health check or full reindex of the memory store |
| `memory-planning-update` | Update session planning state (phases, objectives, progress) |
| `memory-planning-get` | Get the current planning state for a session |
Planning state differs from memories: it stores temporary session data (objectives, phase progress, findings, errors) with a 7-day TTL, while memories are persisted indefinitely and retrieved via semantic search.
## Installation
Install the package from npm:
```bash
npm install @opencode-manager/memory
# or
pnpm add @opencode-manager/memory
```
During installation, the local embedding model (`all-MiniLM-L6-v2`) is downloaded automatically via the `postinstall` script. For API-based embeddings (OpenAI or Voyage), skip the local model and set your provider and API key in the configuration instead.
Then configure opencode to load the plugin. In your `opencode.json`:
```json
{
"plugin": ["@opencode-manager/memory"]
}
```
## Configuration
On first run, the plugin automatically copies the bundled config to your data directory:
- Path: `~/.local/share/opencode/memory/config.json`
- Falls back to: `$XDG_DATA_HOME/opencode/memory/config.json`
You can edit this file to customize settings. The file is created only if it doesn't already exist.
```json
{
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2",
"dimensions": 384
},
"dataDir": "~/.local/share/opencode/memory",
"dedupThreshold": 0.25,
"logging": {
"enabled": false,
"file": "~/.local/share/opencode/memory/logs/memory.log"
}
}
```
For API-based embeddings:
```json
{
"embedding": {
"provider": "openai",
"model": "text-embedding-3-small",
"apiKey": "sk-..."
}
}
```
### Options
#### Embedding
- `embedding.provider` - Embedding provider: `"local"`, `"openai"`, or `"voyage"`
- `embedding.model` - Model name
- local: `"all-MiniLM-L6-v2"` (384d)
- openai: `"text-embedding-3-small"` (1536d), `"text-embedding-3-large"` (3072d), or `"text-embedding-ada-002"` (1536d)
- voyage: `"voyage-code-3"` (1024d) or `"voyage-2"` (1536d)
- `embedding.dimensions` - Vector dimensions (optional, auto-detected for known models)
- `embedding.apiKey` - API key for openai/voyage providers
- `embedding.baseUrl` - Custom endpoint (optional, defaults to provider's official API)
#### Storage
- `dataDir` - Directory for SQLite database storage (default: `"~/.local/share/opencode/memory"`)
- `dedupThreshold` - Similarity threshold for deduplication (0–1, default: `0.25`, clamped to `0.05–0.40`)
#### Logging
- `logging.enabled` - Enable file logging (default: `false`)
- `logging.file` - Log file path (default: `"~/.local/share/opencode/memory/logs/memory.log"`)
When enabled, logs are written to the specified file with timestamps. The log file has a 10MB size limit with automatic rotation.
## Development
```bash
pnpm build # Compile TypeScript to dist/
pnpm test # Run tests
pnpm typecheck # Type check without emitting
```
+20
View File
@@ -0,0 +1,20 @@
{
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2",
"dimensions": 384,
"baseUrl": "",
"apiKey": ""
},
"dedupThreshold": 0.25,
"logging": {
"enabled": false,
"file": ""
},
"compaction": {
"customPrompt": true,
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
}
}
+58
View File
@@ -0,0 +1,58 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.4",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist",
"config.json",
"scripts",
"README.md"
],
"repository": {
"type": "git",
"url": "https://github.com/chriswritescode-dev/opencode-manager.git"
},
"author": "Chris Scott",
"description": "AI-powered memory management plugin for OpenCode - semantic search and persistent knowledge storage",
"keywords": [
"opencode",
"memory",
"semantic-search",
"vector-embeddings",
"ai-agent",
"plugin"
],
"license": "MIT",
"homepage": "https://github.com/chriswritescode-dev/opencode-manager#readme",
"dependencies": {
"@huggingface/transformers": "^3.8.1",
"@opencode-ai/plugin": "^1.2.9",
"sqlite-vec": "0.1.7-alpha.2"
},
"optionalDependencies": {
"sqlite-vec-darwin-arm64": "0.1.7-alpha.2",
"sqlite-vec-darwin-x64": "0.1.7-alpha.2",
"sqlite-vec-linux-arm64": "0.1.7-alpha.2",
"sqlite-vec-linux-x64": "0.1.7-alpha.2",
"sqlite-vec-windows-x64": "0.1.7-alpha.2"
},
"devDependencies": {
"bun-types": "latest",
"typescript": "^5.7.3"
},
"scripts": {
"build": "tsc -p tsconfig.build.json",
"postinstall": "node scripts/download-models.js",
"prepublishOnly": "pnpm build",
"test": "bun test",
"typecheck": "tsc --noEmit"
}
}
@@ -0,0 +1,38 @@
import { mkdirSync, existsSync } from 'fs'
import { homedir, platform } from 'os'
import { join } from 'path'
const xdgDataHome = process.env['XDG_DATA_HOME'] || join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
const cacheDir = join(xdgDataHome, 'opencode', 'memory', 'models')
if (!existsSync(cacheDir)) {
mkdirSync(cacheDir, { recursive: true })
}
async function downloadModel(modelName) {
console.log(`Downloading model: ${modelName}...`)
const { env, pipeline } = await import('@huggingface/transformers')
env.cacheDir = cacheDir
await pipeline('feature-extraction', modelName, { dtype: 'fp32' })
console.log(`Downloaded: ${modelName}`)
}
async function main() {
console.log(`Cache directory: ${cacheDir}`)
const models = [
'sentence-transformers/all-MiniLM-L6-v2',
]
for (const model of models) {
try {
await downloadModel(model)
} catch (error) {
console.error(`Failed to download ${model}:`, error.message)
}
}
console.log('Model download complete.')
}
main()
+112
View File
@@ -0,0 +1,112 @@
import type { AgentDefinition } from './types'
export const codeAgent: AgentDefinition = {
role: 'code',
id: 'ocm-code',
displayName: 'Code',
description: 'Primary coding agent with awareness of project memory and conventions',
mode: 'primary',
systemPrompt: `You are a coding agent with access to a persistent memory system. Your memory stores project conventions, architectural decisions, and contextual knowledge that carries across sessions.
## Memory Integration
You have access to the @ocm-memory subagent for project institutional knowledge.
### When to Invoke Memory
- Before modifying existing code in areas you haven't worked on this session
- When making architectural or design decisions
- When establishing new patterns or conventions
- When unsure about project-specific coding style or preferences
- When the user references past decisions ("we decided to...", "remember when...")
### When to Skip Memory
- Trivial tasks: formatting, simple renames, single-line fixes
- When the user has provided all necessary context in their message
- When continuing work you already have context for in this session
- Simple questions that don't involve project-specific knowledge
### How to Invoke
Ask Memory about the specific topic: "What conventions exist for [area]?" or
"Any decisions or context about [component/pattern]?"
### After Significant Work
If you've made architectural decisions, established patterns, or discovered
important context, invoke Memory to store it for future sessions.
## Working Rules
1. Before making significant changes, invoke @ocm-memory to check for existing conventions and decisions
2. Follow the code style stored in project memory
3. Respect decisions recorded in memory unless explicitly asked to change them
4. When you discover patterns or make decisions, invoke @ocm-memory to capture them for future reference
## Memory Tools
You have direct access to these tools for managing project memory:
1. **memory-read**: Search and retrieve memories
- query: Semantic search query
- scope: Filter by convention/decision/context
- limit: Max results (default 10)
2. **memory-write**: Create new memories
- content: The memory content
- scope: convention | decision | context
3. **memory-edit**: Update existing memories
- id: The memory ID to edit
- content: Updated content
- scope: Optionally change the scope
4. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
5. **memory-health**: Check plugin health or reindex embeddings
- action: "check" (default) or "reindex"
### Direct Use vs. Subagent
Use memory tools directly for simple operations (quick lookups, storing a single fact). Invoke the @ocm-memory subagent for complex memory tasks (multi-query research, resolving contradictions, bulk curation).
## Workflow
### Before Coding
1. Read the relevant files to understand context
2. If working in an unfamiliar area, check memory for conventions and decisions that apply
3. Understand the existing patterns before introducing new ones
### While Coding
1. Follow established conventions from memory — don't invent new patterns when existing ones apply
2. When you make a meaningful architectural choice, store it immediately with memory-write (scope: decision) including the rationale
3. When you discover a pattern the project follows that isn't yet in memory, store it (scope: convention)
4. When you encounter important context (key file locations, integration points, gotchas), store it (scope: context)
### After Coding
1. Verify your changes work (run tests, linting, type checks as appropriate)
2. Review what you built — does it follow the conventions you found in memory?
3. If you established new patterns, store them as conventions for future sessions
## Memory Curation
You are responsible for keeping memory accurate and useful:
- **Store durable knowledge**, not ephemeral task details. "We use Zod for validation" is durable. "Fixed the bug in line 42" is not.
- **Include rationale with decisions**: not just "we use X" but "we use X because Y"
- **Reference file paths** when storing context about project structure
- **Check for duplicates** before writing — use memory-read first to see if similar knowledge already exists
- **Update stale memories** with memory-edit when you discover they're outdated rather than creating duplicates
## Subagents
You can invoke these subagents when needed:
- **@ocm-memory**: For complex memory operations — multi-query research, contradiction resolution, bulk curation, comprehensive memory retrieval across scopes
- **@ocm-review**: For code review against project conventions and memory. Read-only — it provides feedback but never modifies code`,
}
+36
View File
@@ -0,0 +1,36 @@
import type { AgentRole, AgentDefinition, AgentRegistry } from './types'
import { codeAgent } from './code'
import { reviewAgent } from './review'
import { memoryAgent } from './memory'
export const agents: Record<AgentRole, AgentDefinition> = {
code: codeAgent,
review: reviewAgent,
memory: memoryAgent,
}
export function getAgent(role: AgentRole): AgentDefinition | undefined {
return agents[role]
}
export function getAgentById(id: string): AgentDefinition | undefined {
return Object.values(agents).find((agent) => agent.id === id)
}
export function getAllAgents(): AgentDefinition[] {
return Object.values(agents)
}
export function hasAgent(role: AgentRole): boolean {
return role in agents
}
export function createAgentRegistry(): AgentRegistry {
return {
get: getAgent,
getAll: getAllAgents,
has: hasAgent,
}
}
export { type AgentRole, type AgentDefinition, type AgentRegistry, type AgentConfig } from './types'
+224
View File
@@ -0,0 +1,224 @@
import type { AgentDefinition } from './types'
export const memoryAgent: AgentDefinition = {
role: 'memory',
id: 'ocm-memory',
displayName: 'Memory',
description: 'Expert agent for managing project memory - storing and retrieving conventions, decisions, and context',
mode: 'subagent',
systemPrompt: `You are the project's institutional memory. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
## Your Role
You are invoked by other agents (code, review) when they need project-specific context. You are NOT automatically injected into every conversation—other agents must explicitly invoke you when they need memory context. This keeps interactions focused and prevents context pollution.
## The Three Scopes
Every memory belongs to exactly one scope. Choose carefully:
### Convention (how we do things)
Use for:
- Coding style preferences (e.g., "Use named imports only", "Prefer const over let")
- Naming conventions (e.g., "Component files use PascalCase", "Hooks start with 'use'")
- File organization rules (e.g., "Tests live alongside source in __tests__ folder")
- Testing patterns (e.g., "Use describe/it blocks", "Mock external APIs")
- Import/export conventions (e.g., "Barrel files re-export from index.ts")
- Workflow preferences (e.g., "PRs require review", "Commit messages follow conventional commits")
- Error handling approaches (e.g., "Use Result types for fallible operations")
- Code formatting rules (e.g., "4 spaces indent", "Trailing commas")
Be prescriptive with conventions—they are rules to follow.
### Decision (why we chose this)
Use for:
- Architectural choices and the reasoning behind them (e.g., "We chose SQLite over PostgreSQL for simplicity")
- Technology selections (e.g., "Using Bun as the runtime for faster tests")
- Trade-offs considered and why others were rejected (e.g., "Chose Zustand over Redux for simpler boilerplate")
- Design pattern choices (e.g., "Repository pattern for data access")
- Project structure decisions (e.g., "Monorepo with workspace packages")
- API design decisions (e.g., "REST over GraphQL for this use case")
Include the reasoning—not just "we use X" but "we use X because Y". This helps future maintainers understand the context.
### Context (everything else)
Use for:
- Project structure knowledge (e.g., "The frontend lives in /packages/client")
- Key file locations (e.g., "Entry point is src/index.ts")
- Domain-specific terminology (e.g., "User refers to authenticated entity, Guest to unauthenticated")
- Integration points and API contracts (e.g., "Payment service expects amount in cents")
- Known issues and workarounds (e.g., "Hot reload breaks with circular imports—restart required")
- Technical debt notes (e.g., "Auth needs migration to JWT")
- Domain knowledge (e.g., "Prices stored as integers to avoid floating point issues")
Context is reference material—helpful but not binding like conventions.
## Retrieval Protocol
When invoked, assess what the caller needs:
1. **Understand the request**: What files, patterns, or concepts are they working with?
2. **Query strategically**:
- Start with semantic search using memory-read
- Use specific queries: "naming conventions" not "conventions"
- Make multiple focused queries rather than one broad one
3. **Prioritize results**:
- Corrections/warnings first (mistakes to avoid)
- Conventions second (rules that must be followed)
- Decisions third (constraints and rationale)
- Context last (helpful reference)
4. **Check for contradictions**:
- If you find 2+ memories on the same topic, check for conflicts
- Surface contradictions explicitly and recommend which is current
- Report confidence: "2 memories support X, 1 contradicts"
5. **Extract relevant parts**:
- Don't dump raw memories—summarize what's relevant
- Include memory IDs for reference
- Be concise while being complete
## Storage Protocol
When creating memories:
1. **Categorize correctly**:
- Is it a rule to follow? → convention
- Is it explaining why we did something? → decision
- Is it helpful information? → context
2. **Be specific and actionable**:
- Good: "Use named imports: import { Button } from '@/components/ui/button'"
- Bad: "Follow good import practices"
3. **Include reasoning for decisions**:
- Good: "We use Bun because it provides 3-10x faster test execution compared to Jest, which significantly improves dev velocity"
- Bad: "We use Bun"
4. **Reference files when applicable**:
- "The API client lives in src/lib/api.ts and follows the Repository pattern"
- This helps agents locate relevant code
5. **Check for duplicates first**:
- Before creating, use memory-read to see if similar memory exists
- If similar memory exists, update it instead of creating duplicates
6. **Avoid ephemeral information**:
- Don't store: task details, temporary workarounds, session-specific context
- Do store: patterns that apply across sessions, lessons learned
## Curation Rules
Maintain quality over quantity:
1. **Archive outdated memories**:
- If a convention is no longer followed, archive it
- If a decision has been superseded, note the change
2. **Handle contradictions**:
- Surface both sides of a contradiction
- Recommend which is current based on recency and usage
- Help resolve by proposing a merged, updated memory
3. **Merge overlapping memories**:
- If two memories cover similar ground, combine them
- "Use named exports" + "Prefer named over default exports" → single memory about export conventions
4. **Delete exact duplicates**:
- If memory-write reports deduplicated, the work is done
- No need to create identical copies
5. **Acknowledge knowledge gaps**:
- If asked about something with no memories, say so clearly
- "No memories found about testing strategy—would you like to create one?"
## Response Format
When responding to memory queries, use this structure:
\`\`\`
## Relevant Memories
### Conventions (X memories)
- [ID] Memory title/summary
- Full content...
### Decisions (X memories)
- [ID] Memory title/summary
- Full content...
### Context (X memories)
- [ID] Memory title/summary
- Full content...
## Notes
- Any contradictions or updates needed
- Confidence level
- Suggested actions
\`\`\`
## Invocation Guidance
You are invoked when:
- An agent needs to understand project conventions before making changes
- An agent makes an architectural decision that should be recorded
- An agent encounters something worth preserving for future sessions
- Review feedback involves project-specific standards
You are NOT needed for:
- Trivial changes (formatting, simple renames)
- Questions answered by the user's message
- Work the agent already has context for
## Tools You Have Access To
1. **memory-read**: Search and retrieve memories
- query: Semantic search query
- scope: Filter by convention/decision/context
- limit: Max results (default 10)
2. **memory-write**: Create new memories
- content: The memory content
- scope: convention | decision | context
3. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
4. **memory-planning-update**: Update session planning state
- sessionID: The session to update
- objective: Main task/goal (optional)
- current: Current phase or activity (optional)
- next: What comes next (optional)
- phases: Array of {title, status, notes?} (optional)
- findings: Key discoveries (optional)
- errors: Errors to avoid (optional)
Uses merge semantics - only updates fields provided.
5. **memory-planning-get**: Get planning state for a session
- sessionID: The session to retrieve planning for
## Planning State Management
You are responsible for maintaining planning state across sessions:
1. **After compaction** - Extract planning context from the compaction summary:
- Objectives and goals
- Current phase and progress
- Phases completed and remaining
- Key findings and blockers
Use memory-planning-update to store this state for the session.
2. **When asked about progress** - Use memory-planning-get to retrieve and report on session progress.
3. **Guidance**:
- Phases should track: in_progress, completed, pending
- Store findings as they accumulate (architecture decisions, gotchas discovered)
- Track errors to avoid (mistakes made, workarounds needed)
- Mark planning as active when work is ongoing
Your goal is to be the connective tissue between sessions—ensuring knowledge isn't lost and patterns are maintained. Be helpful, be accurate, and keep the memory base clean and useful.`,
}
+48
View File
@@ -0,0 +1,48 @@
import type { AgentDefinition } from './types'
export const reviewAgent: AgentDefinition = {
role: 'review',
id: 'ocm-review',
displayName: 'Memory Review',
description: 'Code review agent that checks against project memory and conventions',
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['write', 'edit', 'apply_patch'],
},
systemPrompt: `You are a code review agent that analyzes code changes against project memory and conventions.
## Your Role
You review code for correctness, style, and adherence to project conventions stored in memory. You do NOT modify code - you only provide feedback and suggestions.
## Memory Integration
Before reviewing, invoke @ocm-memory to check:
- Conventions that apply to the code being reviewed
- Architectural decisions that the code should respect
- Known patterns or anti-patterns for this area of the codebase
Base your review criteria on what is stored in memory. Flag deviations from stored conventions and decisions in your findings.
## Output Format
Provide reviews in a structured format:
### Findings
- **Critical**: Bugs, security issues, breaking changes
- **Warning**: Code smells, potential issues, convention violations
- **Suggestion**: Improvements, best practices
For each finding:
1. File and line reference
2. Description of the issue
3. Suggested fix (if applicable)
## Constraints
- Never modify code directly
- Be constructive and specific
- Reference the specific memory entry when flagging a convention or decision violation
- Temperature is set to 0.0 for precise, factual analysis`,
}
+37
View File
@@ -0,0 +1,37 @@
export type AgentRole = 'code' | 'review' | 'memory'
export interface AgentDefinition {
role: AgentRole
id: string
displayName: string
description: string
defaultModel?: string
systemPrompt: string
mode?: 'primary' | 'subagent' | 'all'
hidden?: boolean
tools?: {
include?: string[]
exclude?: string[]
}
variant?: string
temperature?: number
maxSteps?: number
}
export interface AgentRegistry {
get(role: AgentRole): AgentDefinition | undefined
getAll(): AgentDefinition[]
has(role: AgentRole): boolean
}
export interface AgentConfig {
description: string
model: string
prompt: string
mode?: 'primary' | 'subagent' | 'all'
tools?: Record<string, boolean>
variant?: string
temperature?: number
maxSteps?: number
hidden?: boolean
}
+8
View File
@@ -0,0 +1,8 @@
import type { CacheService } from './types'
import { InMemoryCacheService } from './memory-cache'
export type { CacheService } from './types'
export function createCacheService(): CacheService {
return new InMemoryCacheService()
}
+62
View File
@@ -0,0 +1,62 @@
import type { CacheService } from './types'
interface CacheEntry<T> {
value: T
expiresAt: number
}
export class InMemoryCacheService implements CacheService {
private cache = new Map<string, CacheEntry<unknown>>()
private cleanupInterval: ReturnType<typeof setInterval> | null = null
constructor() {
this.cleanupInterval = setInterval(() => this.cleanup(), 60000)
}
private cleanup(): void {
const now = Date.now()
for (const [key, entry] of this.cache.entries()) {
if (entry.expiresAt < now) {
this.cache.delete(key)
}
}
}
async get<T>(key: string): Promise<T | null> {
const entry = this.cache.get(key) as CacheEntry<T> | undefined
if (!entry) return null
if (entry.expiresAt < Date.now()) {
this.cache.delete(key)
return null
}
return entry.value
}
async set<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {
const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : Date.now() + 86400000
this.cache.set(key, { value, expiresAt })
}
async del(key: string): Promise<void> {
this.cache.delete(key)
}
async invalidatePattern(pattern: string): Promise<void> {
const regex = new RegExp(pattern.replace(/\*/g, '.*'))
for (const key of this.cache.keys()) {
if (regex.test(key)) {
this.cache.delete(key)
}
}
}
destroy(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = null
}
this.cache.clear()
}
}
+7
View File
@@ -0,0 +1,7 @@
export interface CacheService {
get<T>(key: string): Promise<T | null>
set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>
del(key: string): Promise<void>
invalidatePattern(pattern: string): Promise<void>
destroy(): void
}
+75
View File
@@ -0,0 +1,75 @@
import type { AgentRole, AgentDefinition, AgentConfig } from './agents'
const REPLACED_BUILTIN_AGENTS = ['build']
const ENHANCED_BUILTIN_AGENTS: Record<string, { tools: Record<string, boolean> }> = {
plan: {
tools: {
'memory-read': true,
'memory-planning-update': true,
'memory-planning-get': true,
},
},
}
export function createConfigHandler(agents: Record<AgentRole, AgentDefinition>) {
return async (config: Record<string, unknown>) => {
const agentConfigs = createAgentConfigs(agents)
const userAgentConfigs = config.agent as Record<string, AgentConfig> | undefined
const mergedAgents = { ...agentConfigs }
if (userAgentConfigs) {
for (const [name, userConfig] of Object.entries(userAgentConfigs)) {
if (mergedAgents[name]) {
mergedAgents[name] = { ...mergedAgents[name], ...userConfig }
} else {
mergedAgents[name] = userConfig
}
}
}
for (const name of REPLACED_BUILTIN_AGENTS) {
mergedAgents[name] = { ...mergedAgents[name], hidden: true }
}
for (const [name, enhancement] of Object.entries(ENHANCED_BUILTIN_AGENTS)) {
const existing = mergedAgents[name] as AgentConfig | undefined
const existingTools = existing?.tools ?? {}
mergedAgents[name] = {
...existing,
tools: { ...existingTools, ...enhancement.tools },
} as AgentConfig
}
config.agent = mergedAgents
config.default_agent = 'Code'
}
}
function createAgentConfigs(agents: Record<AgentRole, AgentDefinition>): Record<string, AgentConfig> {
const result: Record<string, AgentConfig> = {}
for (const agent of Object.values(agents)) {
const tools: Record<string, boolean> = {}
if (agent.tools?.exclude) {
for (const tool of agent.tools.exclude) {
tools[tool] = false
}
}
result[agent.displayName] = {
description: agent.description,
model: agent.defaultModel ?? '',
prompt: agent.systemPrompt ?? '',
mode: agent.mode ?? 'subagent',
...(Object.keys(tools).length > 0 ? { tools } : {}),
...(agent.variant ? { variant: agent.variant } : {}),
...(agent.temperature !== undefined ? { temperature: agent.temperature } : {}),
...(agent.maxSteps !== undefined ? { maxSteps: agent.maxSteps } : {}),
...(agent.hidden ? { hidden: agent.hidden } : {}),
}
}
return result
}
+118
View File
@@ -0,0 +1,118 @@
import type { EmbeddingProvider } from './types'
interface ModelDefaults {
dimensions: number
endpoint: string
}
const KNOWN_MODELS: Record<string, ModelDefaults> = {
'text-embedding-3-small': { dimensions: 1536, endpoint: 'https://api.openai.com/v1/embeddings' },
'text-embedding-3-large': { dimensions: 3072, endpoint: 'https://api.openai.com/v1/embeddings' },
'text-embedding-ada-002': { dimensions: 1536, endpoint: 'https://api.openai.com/v1/embeddings' },
'voyage-code-3': { dimensions: 1024, endpoint: 'https://api.voyageai.com/v1/embeddings' },
'voyage-2': { dimensions: 1536, endpoint: 'https://api.voyageai.com/v1/embeddings' },
}
const DEFAULT_PROVIDER_ENDPOINTS: Record<string, string> = {
openai: 'https://api.openai.com/v1/embeddings',
voyage: 'https://api.voyageai.com/v1/embeddings',
}
function normalizeBaseUrl(baseUrl: string): string {
const trimmed = baseUrl.replace(/\/+$/, '')
if (trimmed.endsWith('/v1/embeddings')) return trimmed
if (trimmed.endsWith('/v1')) return `${trimmed}/embeddings`
return `${trimmed}/v1/embeddings`
}
export class ApiEmbeddingProvider implements EmbeddingProvider {
private apiKey: string
private model: string
private endpoint: string
readonly dimensions: number
constructor(
provider: 'openai' | 'voyage',
model?: string,
baseUrl?: string,
dimensions?: number,
apiKey?: string
) {
const knownDefaults = model ? KNOWN_MODELS[model] : undefined
this.model = model || (provider === 'openai' ? 'text-embedding-3-small' : 'voyage-code-3')
this.dimensions = dimensions || knownDefaults?.dimensions || 1536
this.endpoint = baseUrl
? normalizeBaseUrl(baseUrl)
: knownDefaults?.endpoint ?? DEFAULT_PROVIDER_ENDPOINTS[provider] ?? 'https://api.openai.com/v1/embeddings'
this.apiKey = apiKey ?? ''
}
get name(): string {
return `api:${this.model}`
}
get ready(): boolean {
return true
}
warmup(): void {}
async embed(texts: string[]): Promise<number[][]> {
const results: number[][] = []
const batchSize = 100
for (let i = 0; i < texts.length; i += batchSize) {
const batch = texts.slice(i, i + batchSize)
const batchResults = await this.embedBatch(batch)
results.push(...batchResults)
}
return results
}
private async embedBatch(texts: string[]): Promise<number[][]> {
const body = { model: this.model, input: texts }
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`
}
const response = await fetch(this.endpoint, {
method: 'POST',
headers,
body: JSON.stringify(body),
})
if (!response.ok) {
const error = await response.text()
throw new Error(`Embedding API error: ${response.status} ${error}`)
}
const data = await response.json() as {
data?: Array<{ embedding: number[] }>
embeddings?: Array<{ embedding: number[] }>
}
const embeddings = data.data || data.embeddings
if (!embeddings) {
throw new Error('Invalid response from embedding API')
}
return embeddings.map(e => e.embedding)
}
async test(): Promise<boolean> {
try {
const result = await this.embed(['test'])
return result.length === 1 && result[0]?.length === this.dimensions
} catch {
return false
}
}
dispose(): void {
// No-op for API-based providers - connections are managed by fetch
}
}
+191
View File
@@ -0,0 +1,191 @@
import { join } from 'path'
import { resolveDataDir } from '../storage/database'
import type { EmbeddingProvider } from './types'
import { acquireEmbeddingServer, isServerRunning, checkServerHealth } from './shared'
import { LocalEmbeddingProvider } from './local'
interface SharedEmbeddingClientConfig {
dataDir?: string
model: string
dimensions: number
gracePeriod?: number
}
type ConnectionState = 'idle' | 'server' | 'local'
export class SharedEmbeddingClient implements EmbeddingProvider {
readonly dimensions: number
private socketPath: string
private modelName: string
private state: ConnectionState = 'idle'
private localProvider: LocalEmbeddingProvider | null = null
private warmupPromise: Promise<void> | null = null
constructor(config: SharedEmbeddingClientConfig) {
this.modelName = config.model
this.dimensions = config.dimensions
this.socketPath = join(config.dataDir ?? resolveDataDir(), 'embedding.sock')
}
get name(): string {
return `shared:local:${this.dimensions}d`
}
get ready(): boolean {
return this.state !== 'idle'
}
warmup(): void {
if (this.state !== 'idle' || this.warmupPromise) return
this.warmupPromise = this.ensureConnected().then(() => {}).catch(() => {
this.warmupPromise = null
})
}
private async ensureConnected(): Promise<boolean> {
if (this.state === 'server') return true
if (this.state === 'local') return true
const dataDir = join(this.socketPath, '..')
const running = await isServerRunning(dataDir)
if (!running) {
const success = await acquireEmbeddingServer({
dataDir,
model: this.modelName,
dimensions: this.dimensions,
})
if (!success) {
return this.createFallbackProvider()
}
}
try {
const response = await this.sendRequest({ action: 'connect' })
if (response && response.status === 'connected') {
this.state = 'server'
return true
}
return this.createFallbackProvider()
} catch {
return this.createFallbackProvider()
}
}
private async createFallbackProvider(): Promise<boolean> {
this.localProvider = new LocalEmbeddingProvider(this.modelName)
await this.localProvider.ensureLoaded()
this.state = 'local'
return true
}
private async sendRequest(request: { action: string; texts?: string[] }): Promise<Record<string, unknown> | null> {
const net = await import('net')
return new Promise((resolve) => {
const client = net.createConnection({ path: this.socketPath })
let data = ''
const timeout = setTimeout(() => {
client.destroy()
resolve(null)
}, 30000)
client.on('connect', () => {
client.write(JSON.stringify(request) + '\n')
})
client.on('data', (chunk: Buffer) => {
data += chunk.toString()
const lines = data.split('\n')
for (const line of lines) {
if (!line.trim()) continue
try {
const response = JSON.parse(line)
clearTimeout(timeout)
client.end()
resolve(response)
return
} catch {
// Continue waiting
}
}
})
client.on('error', () => {
clearTimeout(timeout)
client.destroy()
resolve(null)
})
})
}
async embed(texts: string[]): Promise<number[][]> {
const localProvider = this.localProvider
if (localProvider) {
return localProvider.embed(texts)
}
await this.ensureConnected()
const provider = this.localProvider
if (provider) {
return provider.embed(texts)
}
const response = await this.sendRequest({ action: 'embed', texts })
if (!response || response.error) {
await this.createFallbackProvider()
const fallbackProvider = this.localProvider
if (fallbackProvider) {
return fallbackProvider.embed(texts)
}
return texts.map(() => new Array(this.dimensions).fill(0))
}
return (response.embeddings as number[][]) ?? []
}
async test(): Promise<boolean> {
const localProvider = this.localProvider
if (localProvider) {
return localProvider.test()
}
try {
const health = await checkServerHealth(this.socketPath)
if (health && health.status === 'ok') {
return true
}
await this.ensureConnected()
const testProvider = this.localProvider
if (testProvider) {
return testProvider.test()
}
return false
} catch {
return false
}
}
dispose(): void {
if (this.localProvider) {
this.localProvider.dispose()
this.localProvider = null
this.state = 'idle'
return
}
if (this.state === 'server') {
this.sendRequest({ action: 'disconnect' }).catch(() => {})
}
this.state = 'idle'
}
}
+92
View File
@@ -0,0 +1,92 @@
import { createHash } from 'crypto'
import type { EmbeddingProvider } from './types'
import type { EmbeddingConfig } from '../types'
import { ApiEmbeddingProvider } from './api'
import { LocalEmbeddingProvider } from './local'
import { SharedEmbeddingClient } from './client'
import { resolveDataDir } from '../storage/database'
import type { CacheService } from '../cache/types'
export { checkServerHealth, isServerRunning } from './shared'
export type { EmbeddingProvider } from './types'
function getLocalModelDimensions(model: string): number {
const dimensions: Record<string, number> = {
'all-MiniLM-L6-v2': 384,
}
return dimensions[model] ?? 384
}
function buildProvider(config: EmbeddingConfig): EmbeddingProvider {
switch (config.provider) {
case 'openai':
return new ApiEmbeddingProvider('openai', config.model, config.baseUrl, config.dimensions, config.apiKey)
case 'voyage':
return new ApiEmbeddingProvider('voyage', config.model, config.baseUrl, config.dimensions, config.apiKey)
case 'local': {
const dataDir = config.dataDir ?? resolveDataDir()
const dimensions = config.dimensions ?? getLocalModelDimensions(config.model)
return new SharedEmbeddingClient({
dataDir,
model: config.model,
dimensions,
gracePeriod: config.serverGracePeriod,
})
}
default:
return new ApiEmbeddingProvider('openai', config.model, config.baseUrl, config.dimensions, config.apiKey)
}
}
export function createEmbeddingProvider(config: EmbeddingConfig): EmbeddingProvider {
return buildProvider(config)
}
export interface EmbeddingService {
embedText(text: string): Promise<number[]>
embedTexts(texts: string[]): Promise<number[][]>
}
export function createEmbeddingService(provider: EmbeddingProvider, cache: CacheService): EmbeddingService {
async function embedText(text: string): Promise<number[]> {
const results = await embedTexts([text])
return results[0] ?? new Array(provider.dimensions).fill(0)
}
async function embedTexts(texts: string[]): Promise<number[][]> {
const results: (number[] | undefined)[] = new Array(texts.length).fill(undefined)
const uncached: Array<{ index: number; text: string; hash: string }> = []
for (let i = 0; i < texts.length; i++) {
const text = texts[i] ?? ''
const hash = createHash('sha256').update(text).digest('hex')
const cacheKey = `emb:${hash}`
const cached = await cache.get<number[]>(cacheKey)
if (cached) {
results[i] = cached
} else {
uncached.push({ index: i, text, hash })
}
}
if (uncached.length > 0) {
const uncachedTexts = uncached.map(u => u.text)
const embeddings = await provider.embed(uncachedTexts)
for (let i = 0; i < uncached.length; i++) {
const { index, hash } = uncached[i]!
const embedding = embeddings[i]
results[index] = embedding
const cacheKey = `emb:${hash}`
await cache.set(cacheKey, embedding, 86400)
}
}
return results as number[][]
}
return { embedText, embedTexts }
}
+126
View File
@@ -0,0 +1,126 @@
import { join } from 'path'
import { resolveDataDir } from '../storage/database'
import type { EmbeddingProvider } from './types'
interface LocalModelConfig {
name: string
dimensions: number
}
const LOCAL_MODELS: Record<string, LocalModelConfig> = {
'all-MiniLM-L6-v2': {
name: 'sentence-transformers/all-MiniLM-L6-v2',
dimensions: 384,
},
}
export class LocalEmbeddingProvider implements EmbeddingProvider {
private pipeline: unknown = null
private loadingPromise: Promise<void> | null = null
readonly dimensions: number
private modelName: string
constructor(model: string = 'all-MiniLM-L6-v2') {
let modelConfig = LOCAL_MODELS[model]
if (!modelConfig) {
modelConfig = LOCAL_MODELS['all-MiniLM-L6-v2']
model = 'all-MiniLM-L6-v2'
}
this.dimensions = modelConfig!.dimensions
this.modelName = modelConfig!.name
}
get name(): string {
return `local:${this.dimensions}d`
}
get ready(): boolean {
return this.pipeline !== null
}
warmup(): void {
if (this.pipeline || this.loadingPromise) return
this.loadingPromise = (async () => {
const { env, pipeline } = await import('@huggingface/transformers')
env.cacheDir = join(resolveDataDir(), 'models')
this.pipeline = await pipeline('feature-extraction', this.modelName, {
dtype: 'fp32',
})
})()
this.loadingPromise.catch(() => {
this.loadingPromise = null
})
}
private async loadModel(modelName: string): Promise<void> {
if (this.pipeline) return
this.loadingPromise = (async () => {
const { env, pipeline } = await import('@huggingface/transformers')
env.cacheDir = join(resolveDataDir(), 'models')
this.pipeline = await pipeline('feature-extraction', modelName, {
dtype: 'fp32',
})
})()
return this.loadingPromise
}
async ensureLoaded(): Promise<void> {
if (this.pipeline) return
if (!this.loadingPromise) {
await this.loadModel(this.modelName)
} else {
await this.loadingPromise
}
}
async embed(texts: string[]): Promise<number[][]> {
await this.ensureLoaded()
if (!this.pipeline) {
throw new Error('Embedding model not loaded')
}
const pipeline = this.pipeline as {
(text: string, options: { pooling: string; normalize: boolean }): Promise<unknown>
}
const results: number[][] = []
for (const text of texts) {
try {
const output = await pipeline(text, {
pooling: 'mean',
normalize: true,
}) as { data: Float32Array }
const embedding = Array.from(output.data)
results.push(embedding)
} catch {
results.push(new Array(this.dimensions).fill(0))
}
}
return results
}
async test(): Promise<boolean> {
try {
await this.ensureLoaded()
const result = await this.embed(['test'])
return result.length === 1 && result[0]?.length === this.dimensions
} catch {
return false
}
}
dispose(): void {
if (this.pipeline && typeof (this.pipeline as { dispose?: () => void }).dispose === 'function') {
(this.pipeline as { dispose: () => void }).dispose()
}
this.pipeline = null
this.loadingPromise = null
}
}
+265
View File
@@ -0,0 +1,265 @@
import { createServer } from 'net'
import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { LocalEmbeddingProvider } from './local'
interface ServerConfig {
socketPath: string
pidPath: string
model: string
dimensions: number
gracePeriod: number
}
class EmbeddingServer {
private config: ServerConfig
private provider: LocalEmbeddingProvider | null = null
private clientCount = 0
private gracePeriodTimer: ReturnType<typeof setTimeout> | null = null
private startTime = Date.now()
private server: ReturnType<typeof createServer> | null = null
constructor(config: ServerConfig) {
this.config = config
}
async start(): Promise<void> {
await this.loadModel()
this.writePidFile()
this.startServer()
this.setupSignalHandlers()
}
private async loadModel(): Promise<void> {
this.provider = new LocalEmbeddingProvider(this.config.model)
await this.provider.ensureLoaded()
}
private writePidFile(): void {
writeFileSync(this.config.pidPath, String(process.pid), 'utf-8')
}
private removePidFile(): void {
try {
if (existsSync(this.config.pidPath)) {
unlinkSync(this.config.pidPath)
}
} catch {
// Ignore cleanup errors
}
}
private startServer(): void {
const socketDir = join(this.config.socketPath, '..')
if (!existsSync(socketDir)) {
mkdirSync(socketDir, { recursive: true })
}
if (existsSync(this.config.socketPath)) {
unlinkSync(this.config.socketPath)
}
this.server = createServer((socket) => {
let buffer = ''
socket.on('data', async (data) => {
buffer += data.toString()
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (!line.trim()) continue
try {
const request = JSON.parse(line) as { action: string; texts?: string[] }
const response = await this.handleRequest(request)
socket.write(JSON.stringify(response) + '\n')
} catch (error) {
const errorResponse = {
error: 'Internal server error',
message: error instanceof Error ? error.message : String(error)
}
socket.write(JSON.stringify(errorResponse) + '\n')
}
}
})
socket.on('close', () => {
// Socket closed
})
socket.on('error', (error) => {
console.error('Socket error:', error)
})
})
this.server.listen(this.config.socketPath)
}
private setupSignalHandlers(): void {
process.on('SIGTERM', () => this.shutdown())
process.on('SIGINT', () => this.shutdown())
}
private async handleRequest(request: { action: string; texts?: string[] }): Promise<Record<string, unknown>> {
const { action, texts } = request
switch (action) {
case 'embed':
if (!texts || !Array.isArray(texts)) {
return { error: 'Missing or invalid texts array' }
}
return this.handleEmbed(texts)
case 'health':
return this.handleHealth()
case 'connect':
return this.handleConnect()
case 'disconnect':
return this.handleDisconnect()
default:
return { error: `Unknown action: ${action}` }
}
}
private async handleEmbed(texts: string[]): Promise<Record<string, unknown>> {
if (!this.provider) {
return { error: 'Provider not initialized' }
}
try {
const embeddings = await this.provider.embed(texts)
return { embeddings }
} catch (error) {
return {
error: 'Embedding failed',
details: error instanceof Error ? error.message : String(error)
}
}
}
private handleHealth(): Record<string, unknown> {
return {
status: 'ok',
clients: this.clientCount,
uptime: Date.now() - this.startTime,
dimensions: this.config.dimensions,
model: this.config.model,
}
}
private handleConnect(): Record<string, unknown> {
this.clientCount++
this.cancelGracePeriod()
return {
status: 'connected',
clients: this.clientCount
}
}
private handleDisconnect(): Record<string, unknown> {
this.clientCount = Math.max(0, this.clientCount - 1)
if (this.clientCount === 0) {
this.startGracePeriod()
}
return {
status: 'disconnected',
clients: this.clientCount
}
}
private cancelGracePeriod(): void {
if (this.gracePeriodTimer) {
clearTimeout(this.gracePeriodTimer)
this.gracePeriodTimer = null
}
}
private startGracePeriod(): void {
this.cancelGracePeriod()
this.gracePeriodTimer = setTimeout(() => {
if (this.clientCount === 0) {
this.shutdown()
}
}, this.config.gracePeriod)
}
private shutdown(): void {
this.cancelGracePeriod()
if (this.server) {
this.server.close()
this.server = null
}
try {
if (existsSync(this.config.socketPath)) {
unlinkSync(this.config.socketPath)
}
} catch {
// Ignore cleanup errors
}
this.removePidFile()
if (this.provider) {
this.provider.dispose()
this.provider = null
}
process.exit(0)
}
}
function parseArgs(): ServerConfig {
const args = process.argv.slice(2)
let socketPath = '/tmp/embedding.sock'
let pidPath = '/tmp/embedding.pid'
let model = 'all-MiniLM-L6-v2'
let dimensions = 384
let gracePeriod = 30000
for (let i = 0; i < args.length; i++) {
const arg = args[i]
switch (arg) {
case '--socket':
socketPath = args[++i]
break
case '--pid':
pidPath = args[++i]
break
case '--model':
model = args[++i]
break
case '--dimensions':
dimensions = parseInt(args[++i], 10)
break
case '--grace-period':
gracePeriod = parseInt(args[++i], 10)
break
}
}
return { socketPath, pidPath, model, dimensions, gracePeriod }
}
async function main(): Promise<void> {
const config = parseArgs()
const server = new EmbeddingServer(config)
await server.start()
}
main().catch((error) => {
console.error('Failed to start embedding server:', error)
process.exit(1)
})
+316
View File
@@ -0,0 +1,316 @@
import { existsSync, mkdirSync, rmSync, readFileSync, statSync, unlinkSync } from 'fs'
import { join } from 'path'
import { spawn } from 'child_process'
import * as net from 'net'
export interface SharedEmbeddingConfig {
dataDir: string
model: string
dimensions: number
gracePeriod?: number
}
export async function isServerRunning(dataDir: string): Promise<boolean> {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
if (!existsSync(pidPath) || !existsSync(socketPath)) {
return false
}
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try {
process.kill(pid, 0)
} catch {
return false
}
const health = await checkServerHealth(socketPath)
return health !== null
} catch {
return false
}
}
export async function checkServerHealth(socketPath: string): Promise<{ status: string; clients: number; uptime: number; dimensions: number; model?: string } | null> {
return new Promise((resolve) => {
const client = net.createConnection({ path: socketPath })
let data = ''
const timeout = setTimeout(() => {
client.destroy()
resolve(null)
}, 3000)
client.on('connect', () => {
client.write(JSON.stringify({ action: 'health' }) + '\n')
})
client.on('data', (chunk: Buffer) => {
data += chunk.toString()
const lines = data.split('\n')
for (const line of lines) {
if (!line.trim()) continue
try {
const response = JSON.parse(line)
clearTimeout(timeout)
client.end()
if (response.status === 'ok') {
resolve(response)
} else {
resolve(null)
}
return
} catch {
// Continue waiting
}
}
})
client.on('error', () => {
clearTimeout(timeout)
client.destroy()
resolve(null)
})
})
}
export async function acquireEmbeddingServer(config: SharedEmbeddingConfig): Promise<boolean> {
const { dataDir, model, dimensions, gracePeriod = 30000 } = config
const socketPath = join(dataDir, 'embedding.sock')
const pidPath = join(dataDir, 'embedding.pid')
const lockPath = join(dataDir, 'embedding.startup.lock')
const running = await isServerRunning(dataDir)
if (running) {
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
await killEmbeddingServer(dataDir)
}
}
const lockAcquired = await acquireLock(lockPath)
if (!lockAcquired) {
for (let i = 0; i < 10; i++) {
await sleep(500)
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
}
}
return false
}
try {
if (await isServerRunning(dataDir)) {
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
await killEmbeddingServer(dataDir)
}
}
cleanupStaleFiles(dataDir)
const serverScriptPath = join(__dirname, 'server.js')
if (!existsSync(serverScriptPath)) {
console.error('[memory] Server script not found:', serverScriptPath)
return false
}
const serverProcess = spawn(
'bun',
[
serverScriptPath,
'--socket', socketPath,
'--pid', pidPath,
'--model', model,
'--dimensions', String(dimensions),
'--grace-period', String(gracePeriod),
],
{
detached: true,
stdio: 'ignore',
}
)
serverProcess.unref()
for (let i = 0; i < 30; i++) {
await sleep(500)
const health = await checkServerHealth(socketPath)
if (health !== null) {
return true
}
}
return false
} catch (error) {
console.error('[memory] Failed to start embedding server:', error)
return false
} finally {
releaseLock(lockPath)
}
}
async function acquireLock(lockPath: string): Promise<boolean> {
try {
if (existsSync(lockPath)) {
const lockAge = Date.now() - (statSync(lockPath).mtimeMs)
if (lockAge > 30000) {
rmSync(lockPath, { recursive: true, force: true })
} else {
return false
}
}
const lockDir = join(lockPath, '..')
if (!existsSync(lockDir)) {
mkdirSync(lockDir, { recursive: true })
}
mkdirSync(lockPath)
return true
} catch {
return false
}
}
function releaseLock(lockPath: string): void {
try {
if (existsSync(lockPath)) {
rmSync(lockPath, { recursive: true, force: true })
}
} catch {
// Ignore errors
}
}
export function cleanupStaleFiles(dataDir: string): void {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
try {
if (existsSync(pidPath)) {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try {
process.kill(pid, 0)
} catch {
if (existsSync(pidPath)) {
unlinkSync(pidPath)
}
}
}
} catch {
// Ignore errors
}
try {
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
} catch {
// Ignore errors
}
}
export async function killEmbeddingServer(dataDir: string): Promise<boolean> {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
let pid: number | null = null
try {
if (existsSync(pidPath)) {
pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
}
} catch {
// Ignore read errors
}
if (pid === null) {
return false
}
try {
process.kill(pid, 'SIGTERM')
} catch {
// Process may already be dead
}
for (let i = 0; i < 20; i++) {
await sleep(250)
try {
process.kill(pid, 0)
} catch {
break
}
}
try {
if (existsSync(pidPath)) {
unlinkSync(pidPath)
}
} catch {
// Ignore cleanup errors
}
try {
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
} catch {
// Ignore cleanup errors
}
return true
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
+9
View File
@@ -0,0 +1,9 @@
export interface EmbeddingProvider {
embed(texts: string[]): Promise<number[][]>
readonly dimensions: number
readonly name: string
readonly ready: boolean
test(): Promise<boolean>
warmup(): void
dispose?(): void
}
@@ -0,0 +1,142 @@
import type { PlanningState } from '../types'
export function buildCustomCompactionPrompt(): string {
return `You are generating a continuation context for a coding session with persistent
project memory. Your summary will be the ONLY context after compaction.
Preserve everything needed for seamless continuation.
## CRITICAL - Preserve These Verbatim
1. The current task/objective (quote the user's original request exactly)
2. Active planning state: current phase, completed phases, next steps, blockers
3. ALL file paths being actively worked on (with what's being done)
4. Key decisions made and their rationale
5. Any corrections or gotchas discovered during the session
6. Todo list state (what's done, in progress, pending)
## Structure Your Summary As:
### Active Task
[Verbatim objective + what was happening when compaction fired]
### Planning State
[Phases with status and notes]
### Key Context
[Decisions, constraints, user preferences, corrections]
### Active Files
[filepath -> what's being done to it]
### Next Steps
[What should happen immediately after compaction]
## Rules
- Use specific file paths, phase names - NOT vague references
- State what tools returned, not just that they were called
- Prefer completeness over brevity - this is the agent's entire working memory`
}
export function formatPlanningState(planningState: PlanningState | null): string | null {
if (!planningState) return null
const sections: string[] = []
if (planningState.objective) {
sections.push(`**Objective:** ${planningState.objective}`)
}
if (planningState.current) {
sections.push(`**Current:** ${planningState.current}`)
}
if (planningState.next) {
sections.push(`**Next:** ${planningState.next}`)
}
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
}
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n')
}
export function formatCompactionDiagnostics(stats: {
planningPhases: number
conventions: number
decisions: number
tokensInjected: number
}): string {
const parts: string[] = []
if (stats.planningPhases > 0) {
parts.push(`${stats.planningPhases} planning phase${stats.planningPhases !== 1 ? 's' : ''}`)
}
if (stats.conventions > 0) {
parts.push(`${stats.conventions} convention${stats.conventions !== 1 ? 's' : ''}`)
}
if (stats.decisions > 0) {
parts.push(`${stats.decisions} decision${stats.decisions !== 1 ? 's' : ''}`)
}
if (parts.length === 0) return ''
return `> **Compaction preserved:** ${parts.join(', ')} (~${stats.tokensInjected} tokens injected)`
}
export function estimateTokens(text: string): number {
return Math.ceil(text.length / 4)
}
export function trimToTokenBudget(
content: string,
maxTokens: number,
priority: 'high' | 'medium' | 'low'
): string {
const maxChars = maxTokens * 4
if (content.length <= maxChars) return content
if (priority === 'low') {
return content.slice(0, maxChars) + '...'
}
const lines = content.split('\n')
const trimmed: string[] = []
let currentChars = 0
const skipFromEnd = priority === 'medium' ? Math.floor(lines.length * 0.2) : 0
const linesToUse = skipFromEnd > 0 ? lines.slice(0, -skipFromEnd) : lines
for (const line of linesToUse) {
if (currentChars + line.length + 1 > maxChars) break
trimmed.push(line)
currentChars += line.length + 1
}
if (trimmed.length < linesToUse.length) {
trimmed.push('...')
}
return trimmed.join('\n')
}
+10
View File
@@ -0,0 +1,10 @@
export { createSessionHooks, type SessionHooks } from './session'
export { createKeywordHooks, type KeywordHooks, ACTIVATION_CONTEXT } from './keyword'
export { createParamsHooks, type ParamsHooks } from './params'
export {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
} from './compaction-utils'
+127
View File
@@ -0,0 +1,127 @@
import type { Logger } from '../types'
export interface KeywordHooks {
onMessage: (input: unknown, output: unknown) => Promise<void>
isActivated: (sessionId: string) => boolean
getMode: (sessionId: string) => string | undefined
}
interface TextPart {
type: 'text'
text: string
synthetic?: boolean
ignored?: boolean
}
interface ChatMessageInput {
sessionID?: string
agent?: string
messageID?: string
}
interface ChatMessageOutput {
message?: { id?: string; role: string; sessionID?: string }
parts?: Array<TextPart>
}
interface ActivationState {
activated: boolean
mode?: string
}
const KEYWORD_PATTERNS = [
/remember\s+(this|that)/i,
/recall/i,
/what\s+do\s+you\s+know\s+about/i,
/project\s+memory/i,
/do\s+you\s+remember/i,
/stored\s+memory/i,
/from\s+memory/i,
]
export const ACTIVATION_CONTEXT = `## Project Memory Available
This project has a memory system that stores architectural decisions, conventions, and patterns. You have access to:
- memory-read: Search and retrieve project memories
- memory-write: Store new project memories as suggestions
- memory-delete: Delete a memory by ID
Memory scopes: convention, decision, context
When relevant, use these tools to provide context from the project's knowledge base.`
const MODE_PATTERNS: Record<string, RegExp[]> = {
creative: [
/brainstorm/i,
/be\s+creative/i,
/explore\s+options/i,
/generate\s+ideas/i,
],
deepThink: [
/think\s+hard/i,
/think\s+deeply/i,
/analyze\s+carefully/i,
/think\s+through/i,
],
thorough: [
/go\s+deep/i,
/be\s+thorough/i,
/take\s+your\s+time/i,
],
}
export function createKeywordHooks(logger: Logger): KeywordHooks {
const sessionStateMap = new Map<string, ActivationState>()
return {
async onMessage(input, output) {
const chatInput = input as ChatMessageInput
const chatOutput = output as ChatMessageOutput
const sessionId = chatInput.sessionID
if (!sessionId) return
const existingState = sessionStateMap.get(sessionId)
if (existingState?.activated && existingState.mode) return
const parts = chatOutput.parts ?? []
const textParts = parts.filter((p): p is TextPart => {
if (p.type !== 'text') return false
return typeof p.text === 'string' && p.text.length > 0
})
const userContent = textParts.map(p => p.text).join(' ')
if (!userContent) return
const hasKeyword = KEYWORD_PATTERNS.some((pattern) => pattern.test(userContent))
const matchedModeEntry = Object.entries(MODE_PATTERNS).find(([, patterns]) =>
patterns.some((pattern) => pattern.test(userContent))
)
const matchedMode = matchedModeEntry?.[0]
if (!hasKeyword && !matchedMode) return
const state = sessionStateMap.get(sessionId) ?? { activated: false }
if (hasKeyword && !state.activated) {
logger.log(`Keyword match detected in session ${sessionId}, setting activation flag`)
state.activated = true
}
if (matchedMode && !state.mode) {
logger.log(`Mode pattern detected in session ${sessionId}: ${matchedMode}`)
state.mode = matchedMode
}
sessionStateMap.set(sessionId, state)
},
isActivated(sessionId: string): boolean {
return sessionStateMap.get(sessionId)?.activated ?? false
},
getMode(sessionId: string): string | undefined {
return sessionStateMap.get(sessionId)?.mode
},
}
}
+73
View File
@@ -0,0 +1,73 @@
import type { KeywordHooks } from './keyword'
export interface ParamsHooks {
onParams: (input: unknown, output: unknown) => Promise<void>
}
interface ChatParamsInput {
sessionID?: string
agent: string
}
interface ChatParamsOutput {
temperature?: number
topP?: number
topK?: number
options?: Record<string, any>
}
type ModeConfig = {
temperature?: number
maxSteps?: number
thinkingBudgetTokens?: number
}
const MODE_CONFIGS: Record<string, ModeConfig> = {
creative: {
temperature: 0.8,
},
deepThink: {
thinkingBudgetTokens: 32000,
},
thorough: {
maxSteps: 50,
},
}
export function createParamsHooks(keywordHooks: KeywordHooks): ParamsHooks {
return {
async onParams(input, output) {
const paramsInput = input as ChatParamsInput
const paramsOutput = output as ChatParamsOutput
const sessionId = paramsInput.sessionID
if (!sessionId) return
const mode = keywordHooks.getMode(sessionId)
if (!mode) return
const config = MODE_CONFIGS[mode]
if (!config) return
if (config.temperature !== undefined) {
paramsOutput.temperature = config.temperature
}
if (config.maxSteps !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.maxSteps = config.maxSteps
}
if (config.thinkingBudgetTokens !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.thinking = {
budgetTokens: config.thinkingBudgetTokens,
}
}
},
}
}
+243
View File
@@ -0,0 +1,243 @@
import type { Logger, PlanningState, PreCompactionSnapshot, CompactionConfig } from '../types'
import type { MemoryService } from '../services/memory'
import type { SessionStateService } from '../services/session-state'
import type { PluginInput } from '@opencode-ai/plugin'
import {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
} from './compaction-utils'
export interface SessionHooks {
onMessage: (input: unknown, output: unknown) => Promise<void>
onEvent: (input: { event: { type: string; properties?: Record<string, unknown> } }) => Promise<void>
onCompacting: (
input: { sessionID: string },
output: { context: string[]; prompt?: string }
) => Promise<void>
}
interface ChatMessageInput {
sessionID?: string
}
interface EventInput {
event: {
type: string
properties?: Record<string, unknown>
}
}
interface CompactingInput {
sessionID: string
branch?: string
}
interface CompactingOutput {
context: string[]
prompt?: string
}
const LOGGED_EVENTS = new Set(['session.compacted', 'session.status', 'session.updated', 'session.created'])
function formatEventProperties(props?: Record<string, unknown>): string {
if (!props) return ''
try {
return ' ' + JSON.stringify(props)
} catch {
return ''
}
}
function buildExtractionPrompt(sessionId: string): string {
return `[COMPACTION COMPLETE]
The compaction summary above is now in your context window.
Review the compaction summary and extract any project knowledge worth preserving across sessions. For each item found, use memory-write to store it with the appropriate scope:
- convention: coding style rules, naming patterns, workflow preferences
- decision: architectural choices with their rationale
- context: project structure, key file locations, domain knowledge, known issues
Also extract any planning state (phases, objectives, progress, blockers) from the compaction summary. If found, use memory-planning-update with sessionID "${sessionId}" to store it. This creates continuity across compactions.
Be selective — only store knowledge that will be useful in future sessions. Skip ephemeral task details and session-specific notes.
Check for duplicates before writing (use memory-read to search). If a similar memory already exists, skip it.`
}
const DEFAULT_COMPACTION_CONFIG: CompactionConfig = {
customPrompt: true,
inlinePlanning: true,
maxContextTokens: 4000,
snapshotToKV: true,
}
export function createSessionHooks(
projectId: string,
memoryService: MemoryService,
sessionStateService: SessionStateService,
logger: Logger,
ctx: PluginInput,
config?: CompactionConfig
): SessionHooks {
const initializedSessions = new Set<string>()
const compactionConfig = { ...DEFAULT_COMPACTION_CONFIG, ...config }
return {
async onMessage(input, _output) {
const chatInput = input as ChatMessageInput
const sessionId = chatInput.sessionID
if (!sessionId) return
if (!initializedSessions.has(sessionId)) {
logger.log(`Session initialized: ${sessionId} (project ${projectId})`)
initializedSessions.add(sessionId)
}
},
async onEvent(input: EventInput) {
const { event } = input
if (event && LOGGED_EVENTS.has(event.type)) {
logger.log(`Event received: ${event.type}${formatEventProperties(event.properties)}`)
}
if (event?.type !== 'session.compacted') return
const sessionId = (event.properties?.sessionId as string) ??
(event.properties?.sessionID as string)
if (!sessionId) {
logger.log(`session.compacted event missing sessionId`)
return
}
logger.log(`Session compacted for project ${projectId} - extraction handled by Memory agent`)
ctx.client.session.promptAsync({
path: { id: sessionId },
body: {
agent: 'Memory',
parts: [{ type: 'text', text: buildExtractionPrompt(sessionId) }],
},
}).catch((err) => {
logger.error(`Failed to invoke memory extraction: ${err}`)
})
},
async onCompacting(input: CompactingInput, output: CompactingOutput) {
const { sessionID: sessionId, branch } = input
logger.log(`Compacting hook fired for project ${projectId}, session ${sessionId}`)
try {
const sections: string[] = []
let totalTokens = 0
let planningState: PlanningState | null = null
if (compactionConfig.inlinePlanning) {
planningState = sessionStateService.getPlanningState(sessionId)
if (planningState) {
const planningText = formatPlanningState(planningState)
if (planningText) {
sections.push(`## Planning State\n${planningText}`)
totalTokens += estimateTokens(planningText)
}
logger.log(`Compacting: fetched planning state for session ${sessionId}`)
}
}
if (compactionConfig.snapshotToKV) {
const priorSnapshot = sessionStateService.getCompactionSnapshot(sessionId)
if (priorSnapshot) {
const snapshotParts: string[] = []
snapshotParts.push(`Last compaction: ${new Date(priorSnapshot.timestamp).toLocaleString()}`)
if (priorSnapshot.branch) {
snapshotParts.push(`branch: ${priorSnapshot.branch}`)
}
if (priorSnapshot.planningState) {
const priorPlanningText = formatPlanningState(priorSnapshot.planningState)
if (priorPlanningText) {
snapshotParts.push(`\n### Prior Planning State:\n${priorPlanningText}`)
}
}
sections.push(`## Prior Session Context\n${snapshotParts.join('\n')}`)
totalTokens += estimateTokens(snapshotParts.join('\n'))
logger.log(`Compacting: fetched prior snapshot for session ${sessionId}`)
}
}
const [convMemories, decMemories] = await Promise.all([
memoryService.listByProject(projectId, { scope: 'convention', limit: 10 }),
memoryService.listByProject(projectId, { scope: 'decision', limit: 10 }),
])
const allMemories = [...convMemories, ...decMemories]
logger.log(`Compacting: fetched ${allMemories.length} memories (conv=${convMemories.length}, dec=${decMemories.length})`)
if (allMemories.length > 0) {
const formatScope = (items: typeof allMemories, scope: string) =>
items.filter(m => m.scope === scope).map(m => `- ${m.content}`).join('\n')
const conv = formatScope(allMemories, 'convention')
if (conv) sections.push(`### Conventions\n${conv}`)
const dec = formatScope(allMemories, 'decision')
if (dec) sections.push(`### Decisions\n${dec}`)
}
const maxTokens = compactionConfig.maxContextTokens ?? 4000
let trimmedSections = [...sections]
let currentTokens = totalTokens
for (let i = trimmedSections.length - 1; i >= 0; i--) {
const sectionTokens = estimateTokens(trimmedSections[i]!)
if (currentTokens + sectionTokens > maxTokens) {
const priority = i === 0 ? 'high' : i <= 1 ? 'medium' : 'low'
trimmedSections[i] = trimToTokenBudget(trimmedSections[i]!, maxTokens - currentTokens, priority)
}
currentTokens += estimateTokens(trimmedSections[i]!)
}
trimmedSections = trimmedSections.filter(s => s.length > 0)
if (trimmedSections.length === 0) return
const contextText = `## Project Memory\n\nPreserve these established facts during compaction:\n\n${trimmedSections.join('\n\n')}`
output.context.push(contextText)
if (compactionConfig.customPrompt) {
output.prompt = buildCustomCompactionPrompt()
logger.log(`Compacting: set custom compaction prompt`)
}
if (compactionConfig.snapshotToKV) {
try {
const snapshot: PreCompactionSnapshot = {
timestamp: new Date().toISOString(),
sessionId,
planningState: planningState ?? undefined,
branch,
}
sessionStateService.setCompactionSnapshot(sessionId, projectId, snapshot)
logger.log(`Compacting: stored pre-compaction snapshot`)
} catch (error) {
logger.error(`Failed to store pre-compaction snapshot: ${error}`)
}
}
const diagnostics = formatCompactionDiagnostics({
planningPhases: planningState?.phases?.length ?? 0,
conventions: convMemories.length,
decisions: decMemories.length,
tokensInjected: estimateTokens(trimmedSections.join('\n\n')),
})
if (diagnostics) {
output.context.push(diagnostics)
}
logger.log(`Compacting: injected ${trimmedSections.length} context sections`)
} catch (error) {
logger.error(`Compacting hook failed: ${error}`)
}
},
}
}
+570
View File
@@ -0,0 +1,570 @@
import type { Plugin, PluginInput, Hooks } from '@opencode-ai/plugin'
import { tool } from '@opencode-ai/plugin'
import { agents } from './agents'
import { createConfigHandler } from './config'
import {
createSessionHooks,
createKeywordHooks,
createParamsHooks,
ACTIVATION_CONTEXT,
} from './hooks'
import { join } from 'path'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
import type { MemoryService } from './services/memory'
import { createVecService } from './storage/vec'
import { createEmbeddingProvider, checkServerHealth, isServerRunning } from './embedding'
import { createMemoryService } from './services/memory'
import { createSessionStateService } from './services/session-state'
import { createEmbeddingSyncService } from './services/embedding-sync'
import { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger } from './utils/logger'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger, PlanningState } from './types'
import type { EmbeddingProvider } from './embedding'
import type { Database } from 'bun:sqlite'
import { createNoopVecService } from './storage/vec'
const z = tool.schema
async function getHealthStatus(
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
): Promise<HealthStatus> {
const socketPath = join(dataDir, 'embedding.sock')
let dbStatus: 'ok' | 'error' = 'ok'
let memoryCount = 0
try {
db.prepare('SELECT 1').get()
const row = db.prepare("SELECT COUNT(*) as count FROM memories").get() as { count: number }
memoryCount = row.count
} catch {
dbStatus = 'error'
}
let operational = false
try {
operational = await provider.test()
} catch {
operational = false
}
let serverRunning = false
let serverHealth: { status: string; clients: number; uptime: number } | null = null
try {
serverRunning = await isServerRunning(dataDir)
if (serverRunning) {
serverHealth = await checkServerHealth(socketPath)
}
} catch {
serverRunning = false
}
const configuredModel = {
model: config.embedding.model,
dimensions: config.embedding.dimensions ?? provider.dimensions,
}
let currentModel: { model: string; dimensions: number } | null = null
try {
const metadata = createMetadataQuery(db)
const stored = metadata.getEmbeddingModel()
if (stored) {
currentModel = { model: stored.model, dimensions: stored.dimensions }
}
} catch {
// Ignore
}
const needsReindex = !currentModel ||
currentModel.model !== configuredModel.model ||
currentModel.dimensions !== configuredModel.dimensions
const overallStatus: 'ok' | 'degraded' | 'error' = dbStatus === 'error'
? 'error'
: !operational
? 'degraded'
: 'ok'
return {
dbStatus,
memoryCount,
operational,
serverRunning,
serverHealth,
configuredModel,
currentModel,
needsReindex,
overallStatus,
}
}
function formatHealthStatus(status: HealthStatus, provider: EmbeddingProvider): string {
const { dbStatus, memoryCount, operational, serverRunning, serverHealth, configuredModel, currentModel, needsReindex, overallStatus } = status
const embeddingStatus: 'ok' | 'error' = operational ? 'ok' : 'error'
const lines: string[] = [
`Memory Plugin Health: ${overallStatus.toUpperCase()}`,
'',
`Embedding: ${embeddingStatus}`,
` Provider: ${provider.name} (${provider.dimensions}d)`,
` Operational: ${operational}`,
` Server running: ${serverRunning}`,
]
if (serverHealth) {
lines.push(` Clients: ${serverHealth.clients}, Uptime: ${Math.round(serverHealth.uptime / 1000)}s`)
}
lines.push('')
lines.push(`Database: ${dbStatus}`)
lines.push(` Total memories: ${memoryCount}`)
lines.push('')
lines.push(`Model: ${needsReindex ? 'drift' : 'ok'}`)
lines.push(` Configured: ${configuredModel.model} (${configuredModel.dimensions}d)`)
if (currentModel) {
lines.push(` Indexed: ${currentModel.model} (${currentModel.dimensions}d)`)
} else {
lines.push(' Indexed: none')
}
if (needsReindex) {
lines.push(' Reindex required - run memory-health with action "reindex"')
} else {
lines.push(' In sync')
}
return lines.join('\n')
}
async function executeHealthCheck(
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
): Promise<string> {
const status = await getHealthStatus(db, config, provider, dataDir)
return formatHealthStatus(status, provider)
}
async function executeReindex(
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
): Promise<string> {
const configuredModel = config.embedding.model
const configuredDimensions = config.embedding.dimensions ?? provider.dimensions
let operational = false
try {
operational = await provider.test()
} catch {
operational = false
}
if (!operational) {
return 'Reindex failed: embedding provider is not operational. Check your API key and model configuration.'
}
const result = await memoryService.reindex()
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
metadata.setEmbeddingModel(configuredModel, configuredDimensions)
}
const lines: string[] = [
'Reindex complete',
'',
`Total memories: ${result.total}`,
`Embedded: ${result.success}`,
`Failed: ${result.failed}`,
'',
`Model: ${configuredModel} (${configuredDimensions}d)`,
]
if (result.failed > 0) {
lines.push(`WARNING: ${result.failed} memories failed to embed`)
}
return lines.join('\n')
}
async function autoValidateOnLoad(
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
logger: Logger,
): Promise<void> {
const status = await getHealthStatus(db, config, provider, dataDir)
if (status.overallStatus === 'error') {
logger.log('Auto-validate: unhealthy (db error), skipping')
return
}
if (!status.needsReindex) {
logger.log('Auto-validate: healthy, no action needed')
return
}
if (!status.operational) {
logger.log('Auto-validate: reindex needed but provider not operational, skipping')
return
}
logger.log('Auto-validate: model drift detected, starting reindex')
const result = await memoryService.reindex()
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
metadata.setEmbeddingModel(
config.embedding.model,
config.embedding.dimensions ?? provider.dimensions,
)
}
logger.log(`Auto-validate: reindex complete (total=${result.total}, success=${result.success}, failed=${result.failed})`)
}
export function createMemoryPlugin(config: PluginConfig): Plugin {
return async (input: PluginInput): Promise<Hooks> => {
const { directory, project } = input
const projectId = project.id
const loggingConfig = config.logging
const logger = createLogger({
enabled: loggingConfig?.enabled ?? false,
file: loggingConfig?.file ?? resolveLogPath(),
})
logger.log(`Initializing plugin for directory: ${directory}, projectId: ${projectId}`)
const provider = createEmbeddingProvider(config.embedding)
provider.warmup()
const dataDir = config.dataDir ?? resolveDataDir()
const db = initializeDatabase(dataDir)
const dimensions = config.embedding.dimensions ?? provider.dimensions
const noopVec = createNoopVecService()
const memoryService = await createMemoryService({
db,
provider,
vec: noopVec,
logger,
})
const sessionStateService = createSessionStateService(db, logger)
sessionStateService.startCleanupInterval()
sessionStateService.deleteExpired()
if (config.dedupThreshold) {
memoryService.setDedupThreshold(config.dedupThreshold)
}
const initPromise = createVecService(db, dataDir, dimensions)
.then(async (vec) => {
memoryService.setVecService(vec)
if (!vec.available) {
logger.log('Vec service unavailable, skipping embedding sync')
return
}
logger.log('Vec service initialized')
const embeddingSync = createEmbeddingSyncService(memoryService, logger)
await embeddingSync.start().catch((err: unknown) => {
logger.error('Embedding sync failed', err)
})
await autoValidateOnLoad(memoryService, db, config, provider, dataDir, logger)
})
.catch((err: unknown) => {
logger.error('Vec service initialization failed', err)
})
const compactionConfig: CompactionConfig | undefined = config.compaction
const sessionHooks = createSessionHooks(projectId, memoryService, sessionStateService, logger, input, compactionConfig)
const keywordHooks = createKeywordHooks(logger)
const paramsHooks = createParamsHooks(keywordHooks)
const scopeEnum = z.enum(['convention', 'decision', 'context'])
let cleaned = false
const cleanup = async () => {
if (cleaned) return
cleaned = true
logger.log('Cleaning up plugin resources...')
await memoryService.destroy()
sessionStateService.destroy()
closeDatabase(db)
logger.log('Plugin cleanup complete')
}
process.once('exit', cleanup)
process.once('SIGINT', cleanup)
process.once('SIGTERM', cleanup)
const getCleanup = cleanup
return {
getCleanup,
tool: {
'memory-read': tool({
description: 'Search and retrieve project memories',
args: {
query: z.string().optional().describe('Semantic search query'),
scope: scopeEnum.optional().describe('Filter by scope'),
limit: z.number().optional().default(10).describe('Max results'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-read: query="${args.query ?? 'none'}", scope=${args.scope}, limit=${args.limit}`)
let results
if (args.query) {
const searchResults = await memoryService.search(args.query, projectId, {
scope: args.scope,
limit: args.limit,
})
results = searchResults.map((r) => r.memory)
} else {
results = memoryService.listByProject(projectId, {
scope: args.scope,
limit: args.limit,
})
}
logger.log(`memory-read: returned ${results.length} results`)
if (results.length === 0) {
return 'No memories found.'
}
const formatted = results.map(
(m: any) => `[${m.id}] (${m.scope}) - Created ${new Date(m.createdAt).toISOString().split('T')[0]}\n${m.content}`
)
return `Found ${results.length} memories:\n\n${formatted.join('\n\n')}`
},
}),
'memory-write': tool({
description: 'Store a new project memory',
args: {
content: z.string().describe('The memory content to store'),
scope: scopeEnum.describe('Memory scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-write: scope=${args.scope}, content="${args.content?.substring(0, 80)}"`)
const result = await memoryService.create({
projectId,
scope: args.scope,
content: args.content,
})
logger.log(`memory-write: created id=${result.id}, deduplicated=${result.deduplicated}`)
return `Memory stored (ID: #${result.id}, scope: ${args.scope}).${result.deduplicated ? ' (matched existing memory)' : ''}`
},
}),
'memory-edit': tool({
description: 'Edit an existing project memory',
args: {
id: z.number().describe('The memory ID to edit'),
content: z.string().describe('The updated memory content'),
scope: scopeEnum.optional().describe('Change the scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-edit: id=${args.id}, content="${args.content?.substring(0, 80)}"`)
const memory = memoryService.getById(args.id)
if (!memory) {
logger.log(`memory-edit: id=${args.id} not found`)
return `Memory #${args.id} not found.`
}
await memoryService.update(args.id, {
content: args.content,
...(args.scope && { scope: args.scope }),
})
logger.log(`memory-edit: updated id=${args.id}`)
return `Updated memory #${args.id} (scope: ${args.scope ?? memory.scope}).`
},
}),
'memory-delete': tool({
description: 'Delete a project memory',
args: {
id: z.number().describe('The memory ID to delete'),
},
execute: async (args) => {
const id = args.id
logger.log(`memory-delete: id=${id}`)
const memory = memoryService.getById(id)
if (!memory) {
logger.log(`memory-delete: id=${id} not found`)
return `Memory #${id} not found.`
}
await memoryService.delete(id)
logger.log(`memory-delete: deleted id=${id}`)
return `Deleted memory #${id}: "${memory.content.substring(0, 50)}..." (${memory.scope})`
},
}),
'memory-health': tool({
description: 'Check memory plugin health or trigger a reindex of all embeddings. Use action "check" (default) to view status, or "reindex" to regenerate all embeddings when model has changed or embeddings are missing.',
args: {
action: z.enum(['check', 'reindex']).optional().default('check').describe('Action to perform: "check" for health status, "reindex" to regenerate embeddings'),
},
execute: async (args) => {
await initPromise
if (args.action === 'reindex') {
return executeReindex(memoryService, db, config, provider)
}
return executeHealthCheck(db, config, provider, dataDir)
},
}),
'memory-planning-update': tool({
description: 'Update the session planning state (phases, objectives, progress). Merge new fields with existing state.',
args: {
sessionID: z.string().describe('The session ID to update'),
objective: z.string().optional().describe('The main task/goal'),
current: z.string().optional().describe('Current phase or activity'),
next: z.string().optional().describe('What comes next'),
phases: z.array(z.object({
title: z.string(),
status: z.string(),
notes: z.string().optional(),
})).optional().describe('Phase list with status'),
findings: z.array(z.string()).optional().describe('Key discoveries'),
errors: z.array(z.string()).optional().describe('Errors to avoid'),
},
execute: async (args) => {
await initPromise
const sessionId = args.sessionID
logger.log(`memory-planning-update: session=${sessionId}`)
const existing = sessionStateService.getPlanningState(sessionId)
const merged: typeof existing = {
...(existing ?? {}),
...(args.objective !== undefined && { objective: args.objective }),
...(args.current !== undefined && { current: args.current }),
...(args.next !== undefined && { next: args.next }),
...(args.phases !== undefined && { phases: args.phases }),
...(args.findings !== undefined && {
findings: [...new Set([...(existing?.findings ?? []), ...args.findings])]
}),
...(args.errors !== undefined && {
errors: [...new Set([...(existing?.errors ?? []), ...args.errors])]
}),
active: true,
}
sessionStateService.setPlanningState(sessionId, projectId, merged as PlanningState)
const hasPhases = merged?.phases && merged.phases.length > 0
const summary = [
merged?.objective && `objective: ${merged.objective}`,
merged?.current && `current: ${merged.current}`,
hasPhases && `${merged.phases!.length} phases`,
].filter(Boolean).join(', ')
logger.log(`memory-planning-update: stored for session ${sessionId}`)
return `Planning state updated for session ${sessionId}. ${summary || 'No data provided'}`
},
}),
'memory-planning-get': tool({
description: 'Get the current planning state for a session',
args: {
sessionID: z.string().describe('The session ID to retrieve planning state for'),
},
execute: async (args) => {
await initPromise
const sessionId = args.sessionID
logger.log(`memory-planning-get: session=${sessionId}`)
const planningState = sessionStateService.getPlanningState(sessionId)
if (!planningState) {
return 'No planning state found for this session'
}
const sections: string[] = []
if (planningState.objective) sections.push(`**Objective:** ${planningState.objective}`)
if (planningState.current) sections.push(`**Current:** ${planningState.current}`)
if (planningState.next) sections.push(`**Next:** ${planningState.next}`)
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
}
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n') || 'Planning state exists but is empty'
},
}),
},
config: createConfigHandler(agents),
'chat.message': async (input, output) => {
await keywordHooks.onMessage(input, output)
await sessionHooks.onMessage(input, output)
},
'chat.params': paramsHooks.onParams,
'experimental.chat.system.transform': async (input, output) => {
const transformInput = input as { sessionID?: string }
const transformOutput = output as { system: string[] }
const sessionId = transformInput.sessionID
if (!sessionId) return
if (!keywordHooks.isActivated(sessionId)) return
transformOutput.system.push(ACTIVATION_CONTEXT)
},
event: async (input) => {
const eventInput = input as { event: { type: string; properties?: Record<string, unknown> } }
if (eventInput.event?.type === 'server.instance.disposed') {
cleanup()
return
}
await sessionHooks.onEvent(eventInput)
},
'experimental.session.compacting': async (input, output) => {
logger.log(`Compacting triggered`)
await sessionHooks.onCompacting(
input as { sessionID: string; branch?: string },
output as { context: string[]; prompt?: string }
)
},
} as Hooks & { getCleanup: () => Promise<void> }
}
}
const plugin: Plugin = async (input: PluginInput): Promise<Hooks> => {
const config = loadPluginConfig()
const factory = createMemoryPlugin(config)
return factory(input)
}
export default plugin
export type { PluginConfig, CompactionConfig } from './types'
@@ -0,0 +1,175 @@
import type { MemoryService } from './memory'
import type { Logger } from '../types'
export interface EmbeddingSyncOptions {
batchSize?: number
maxRetries?: number
}
export interface EmbeddingSyncResult {
total: number
embedded: number
failed: number
}
export class EmbeddingSyncService {
private memoryService: MemoryService
private logger?: Logger
private batchSize: number
private maxRetries: number
private syncInProgress: boolean = false
private static readonly MAX_ITERATIONS = 100
constructor(memoryService: MemoryService, logger?: Logger, options: EmbeddingSyncOptions = {}) {
this.memoryService = memoryService
this.logger = logger
this.batchSize = options.batchSize ?? 50
this.maxRetries = options.maxRetries ?? 3
}
async start(): Promise<void> {
this.logger?.log('[embedding-sync] Starting initial sync...')
await this.syncAll()
}
async syncAll(): Promise<EmbeddingSyncResult> {
if (this.syncInProgress) {
this.logger?.log('[embedding-sync] Sync already in progress, skipping')
return { total: 0, embedded: 0, failed: 0 }
}
this.syncInProgress = true
let total = 0
let embedded = 0
let failed = 0
try {
let pending = this.memoryService.countMemoriesWithoutEmbeddings()
let iterations = 0
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
iterations++
const memories = this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
let batchSuccess = 0
let batchFailed = 0
for (const memory of memories) {
let success = false
let attempts = 0
while (!success && attempts < this.maxRetries) {
success = await this.memoryService.embedMemory(memory.id, memory.content)
attempts++
if (!success && attempts < this.maxRetries) {
this.logger?.log(`[embedding-sync] Retrying memory ${memory.id} (attempt ${attempts + 1}/${this.maxRetries})`)
}
}
total++
if (success) {
embedded++
batchSuccess++
} else {
failed++
batchFailed++
this.logger?.error(`[embedding-sync] Failed to embed memory ${memory.id} after ${this.maxRetries} attempts`)
}
}
if (batchSuccess === 0 && batchFailed > 0) {
this.logger?.error('[embedding-sync] No memories embedded in this batch, stopping to prevent infinite loop')
break
}
pending = this.memoryService.countMemoriesWithoutEmbeddings()
if (pending > 0) {
this.logger?.log(`[embedding-sync] Progress: ${embedded} embedded, ${failed} failed, ${pending} remaining`)
}
}
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
this.logger?.error('[embedding-sync] Reached max iterations, stopping sync')
}
this.logger?.log(`[embedding-sync] Complete: ${embedded} embedded, ${failed} failed`)
} catch (error) {
this.logger?.error('[embedding-sync] Sync error', error)
} finally {
this.syncInProgress = false
}
return { total, embedded, failed }
}
async syncProject(projectId: string): Promise<EmbeddingSyncResult> {
let total = 0
let embedded = 0
let failed = 0
try {
let pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
let iterations = 0
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
iterations++
const memories = this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
let batchSuccess = 0
let batchFailed = 0
for (const memory of memories) {
let success = false
let attempts = 0
while (!success && attempts < this.maxRetries) {
success = await this.memoryService.embedMemory(memory.id, memory.content)
attempts++
if (!success && attempts < this.maxRetries) {
await new Promise(resolve => setTimeout(resolve, 100))
}
}
total++
if (success) {
embedded++
batchSuccess++
} else {
failed++
batchFailed++
}
}
if (batchSuccess === 0 && batchFailed > 0) {
this.logger?.error('[embedding-sync] No memories embedded in this batch, stopping to prevent infinite loop')
break
}
pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
}
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
this.logger?.error('[embedding-sync] Reached max iterations, stopping sync')
}
} catch (error) {
this.logger?.error(`[embedding-sync] Sync error for project ${projectId}`, error)
}
return { total, embedded, failed }
}
isSyncInProgress(): boolean {
return this.syncInProgress
}
}
export function createEmbeddingSyncService(
memoryService: MemoryService,
logger?: Logger,
options?: EmbeddingSyncOptions
): EmbeddingSyncService {
return new EmbeddingSyncService(memoryService, logger, options)
}
+295
View File
@@ -0,0 +1,295 @@
import { Database } from 'bun:sqlite'
import { createMemoryQuery, type CreateMemoryInput, type UpdateMemoryInput, type MemorySearchResult } from '../storage'
import type { VecService } from '../storage/vec-types'
import { createNoopVecService } from '../storage/vec'
import { type EmbeddingService, type EmbeddingProvider, createEmbeddingService } from '../embedding'
import { type CacheService, createCacheService } from '../cache'
import type { Memory, MemoryScope, MemoryStats, Logger } from '../types'
const DEFAULT_DEDUP_THRESHOLD = 0.25
function createNoopEmbeddingProvider(): EmbeddingProvider {
return {
dimensions: 0,
name: 'noop',
ready: false,
embed: async () => [],
test: async () => false,
warmup: () => {},
}
}
export interface MemoryServiceDeps {
db: Database
provider?: EmbeddingProvider
embeddingService: EmbeddingService
cache: CacheService
vec?: VecService
logger?: Logger
}
export class MemoryService {
private queries: ReturnType<typeof createMemoryQuery>
private dedupThreshold: number = DEFAULT_DEDUP_THRESHOLD
private embeddingService: EmbeddingService
private provider: EmbeddingProvider
private cache: CacheService
private vec: VecService
private db: Database
private logger?: Logger
constructor(deps: MemoryServiceDeps) {
this.db = deps.db
this.provider = deps.provider ?? createNoopEmbeddingProvider()
this.embeddingService = deps.embeddingService
this.cache = deps.cache
this.vec = deps.vec ?? createNoopVecService()
this.logger = deps.logger
this.queries = createMemoryQuery(this.db, this.vec, deps.logger)
}
setDedupThreshold(threshold: number): void {
this.dedupThreshold = Math.max(0.05, Math.min(0.40, threshold))
}
setVecService(vec: VecService): void {
this.vec = vec
this.queries = createMemoryQuery(this.db, this.vec, this.logger)
}
async create(input: CreateMemoryInput): Promise<{ id: number; deduplicated: boolean }> {
const existingMemory = this.queries.getByContent(input.projectId, input.content)
if (existingMemory) {
return { id: existingMemory.id, deduplicated: true }
}
const embedding = await this.embeddingService.embedText(input.content)
const similar = await this.queries.findSimilar(embedding, input.projectId, this.dedupThreshold, 1)
if (similar.length > 0) {
return { id: similar[0]!.id, deduplicated: true }
}
try {
this.db.exec('BEGIN IMMEDIATE')
const duplicateCheck = this.queries.getByContent(input.projectId, input.content)
if (duplicateCheck) {
this.db.exec('COMMIT')
return { id: duplicateCheck.id, deduplicated: true }
}
const memoryId = this.queries.createInDb(input)
this.db.exec('COMMIT')
if (this.vec.available && embedding.length > 0) {
try {
await this.vec.insert(embedding, memoryId, input.projectId)
} catch (error) {
this.queries.logError?.('Failed to insert embedding for memory', error)
}
}
await this.invalidateCache(input.projectId)
return { id: memoryId, deduplicated: false }
} catch (error) {
try {
this.db.exec('ROLLBACK')
} catch {
// Ignore rollback errors
}
throw error
}
}
async update(id: number, input: UpdateMemoryInput): Promise<void> {
const existing = this.queries.getById(id)
if (!existing) {
throw new Error(`Memory ${id} not found`)
}
this.queries.update(id, input)
if (input.content !== undefined) {
const embedding = await this.embeddingService.embedText(input.content)
await this.queries.updateEmbedding(id, embedding)
}
await this.invalidateCache(existing.projectId)
}
async delete(id: number): Promise<void> {
const existing = this.queries.getById(id)
if (!existing) {
throw new Error(`Memory ${id} not found`)
}
await this.queries.delete(id)
await this.invalidateCache(existing.projectId)
}
getById(id: number): Memory | undefined {
const memory = this.queries.getById(id)
if (memory) {
this.queries.trackAccess(id)
}
return memory
}
listByProject(
projectId: string,
filters?: {
scope?: MemoryScope
limit?: number
offset?: number
}
): Memory[] {
const memories = this.queries.listByProject(projectId, filters)
memories.forEach((m: Memory) => this.queries.trackAccess(m.id))
return memories
}
listAll(
filters?: {
projectId?: string
scope?: MemoryScope
limit?: number
offset?: number
}
): Memory[] {
const memories = this.queries.listAll(filters)
memories.forEach((m: Memory) => this.queries.trackAccess(m.id))
return memories
}
async search(
query: string,
projectId?: string,
filters?: {
scope?: MemoryScope
limit?: number
}
): Promise<MemorySearchResult[]> {
const embedding = await this.embeddingService.embedText(query)
const results = await this.queries.search(embedding, projectId, filters)
results.forEach((r) => this.queries.trackAccess(r.memory.id))
return results
}
getStats(projectId: string): MemoryStats {
const stats = this.queries.getStats(projectId)
return {
projectId,
total: stats.total,
byScope: stats.byScope,
}
}
async deleteByProject(projectId: string): Promise<void> {
await this.queries.deleteByProject(projectId)
await this.invalidateCache(projectId)
}
async deleteByFilePath(projectId: string, filePath: string): Promise<void> {
await this.queries.deleteByFilePath(projectId, filePath)
await this.invalidateCache(projectId)
}
countByProject(projectId: string): number {
return this.queries.countByProject(projectId)
}
getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Memory[] {
return this.queries.getMemoriesWithoutEmbeddings(projectId, limit)
}
countMemoriesWithoutEmbeddings(projectId?: string): number {
return this.queries.countMemoriesWithoutEmbeddings(projectId)
}
async embedMemory(memoryId: number, content: string): Promise<boolean> {
try {
const embedding = await this.embeddingService.embedText(content)
if (embedding.length > 0) {
await this.queries.updateEmbedding(memoryId, embedding)
return true
}
return false
} catch {
return false
}
}
async reindex(projectId?: string): Promise<{ total: number; success: number; failed: number }> {
const allMemories = projectId
? this.queries.listByProject(projectId, { limit: 10000 })
: this.queries.listAll({ limit: 10000 })
let success = 0
let failed = 0
const batchSize = 50
for (let i = 0; i < allMemories.length; i += batchSize) {
const batch = allMemories.slice(i, i + batchSize)
const texts = batch.map(m => m.content)
try {
const embeddings = await this.embeddingService.embedTexts(texts)
for (let j = 0; j < batch.length; j++) {
try {
await this.queries.updateEmbedding(batch[j]!.id, embeddings[j]!)
success++
} catch {
failed++
}
}
} catch {
failed += batch.length
}
}
if (projectId) {
await this.invalidateCache(projectId)
} else {
await this.invalidateCache('*')
}
return { total: allMemories.length, success, failed }
}
private async invalidateCache(projectId: string): Promise<void> {
try {
await this.cache.invalidatePattern(`mem:project:${projectId}:*`)
} catch {
// Silent failure
}
}
async destroy(): Promise<void> {
this.vec.dispose()
this.cache.destroy()
if (this.provider.dispose) {
await this.provider.dispose()
}
}
}
export interface CreateMemoryServiceOptions {
db: Database
provider: EmbeddingProvider
vec: VecService
logger?: Logger
}
export async function createMemoryService(options: CreateMemoryServiceOptions): Promise<MemoryService> {
const cache = createCacheService()
const embeddingService = createEmbeddingService(options.provider, cache)
return new MemoryService({
db: options.db,
provider: options.provider,
embeddingService,
cache,
vec: options.vec,
logger: options.logger,
})
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more