feat: add workspace plugin for OpenCode TUI integration

- Add @opencode-manager/workspace-plugin package
- Add API tokens management with scoped access control
- Add workspace-plugin routes for project discovery
- Add bearer token authentication for external access
- Add proxy WebSocket support for remote workspaces
- Add frontend UI for API token management
- Update documentation with workspace plugin guide
This commit is contained in:
CS committed 2026-04-20 18:31:22 -04:00
1 parent 0836e324a3
commit d5342ecd91
118 files changed
+7831 -1715

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
# @opencode-manager/workspace-plugin
Connect your local OpenCode TUI to a running opencode-manager instance and use its projects as remote workspaces.
## Installation
Add the plugin to your `opencode.json` configuration:
```json
{
"plugin": [
["@opencode-manager/workspace-plugin", {
"url": "https://manager.example.com",
"token": "<bearer token from manager settings>"
}]
]
}
```
## Configuration
### Options
- `url` (required): The base URL of your opencode-manager instance
- `token` (required): Bearer token created from the manager's Settings page
### Environment Variables
As an alternative to configuring in `opencode.json`, you can use:
- `OPENCODE_MANAGER_URL`: The base URL of your opencode-manager instance
- `OPENCODE_MANAGER_TOKEN`: Bearer token for authentication
## Usage
Once configured, the plugin will automatically discover all projects in your opencode-manager instance and register them as remote workspaces. Each project will appear in the OpenCode TUI workspace picker as `manager:<slug>`.
### Creating a Bearer Token
1. Open your opencode-manager web UI
2. Navigate to Settings → API Tokens
3. Click "Create Token"
4. Give it a name (e.g., "OpenCode TUI")
5. Copy the token immediately (it won't be shown again)
6. Paste it into your `opencode.json` or set `OPENCODE_MANAGER_TOKEN`
### Token Scope
Tokens created for the workspace plugin have the `workspace-plugin` scope by default. This restricts their access to only the workspace plugin endpoints.
## How It Works
1. On startup, the plugin calls `GET /api/workspace-plugin/projects` on the manager
2. For each project returned, it registers a `WorkspaceAdaptor` with type `manager:<slug>`
3. When you select a workspace in the TUI, the adaptor provides:
- Remote target URL: `<manager>/api/opencode`
- Authorization header: `Bearer <token>`
- Project slug header: `x-opencode-manager-project: <slug>`
The manager then proxies requests to the embedded OpenCode server with the appropriate `?directory=` parameter.
## Security Notes
- Bearer tokens are stored hashed (SHA-256) in the manager database
- Tokens are shown only once on creation
- Tokens can be revoked at any time from the Settings page
- Tokens bypass CORS origin requirements (explicit opt-in authentication)
@@ -0,0 +1,26 @@
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'
const __dirname = dirname(fileURLToPath(import.meta.url))
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: __dirname,
},
},
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
ignores: ['dist/**', 'node_modules/**'],
}
)
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@opencode-manager/workspace-plugin",
"version": "0.1.0",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"peerDependencies": {
"@opencode-ai/plugin": ">=1.14.0",
"@opencode-ai/sdk": ">=1.14.0"
},
"devDependencies": {
"@opencode-ai/plugin": "1.14.19",
"@opencode-ai/sdk": "1.14.19",
"@types/bun": "latest",
"typescript": "^5",
"vitest": "^3.2.4",
"zod": "^4.1.12"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest",
"lint": "eslint . --ext .ts"
}
}
+18
View File
@@ -0,0 +1,18 @@
import type { ManagerProject } from "./types.js"
export class ManagerClient {
constructor(private readonly baseUrl: string, private readonly token: string) {}
private headers(): Record<string, string> {
return { Authorization: `Bearer ${this.token}`, "content-type": "application/json" }
}
async listProjects(): Promise<ManagerProject[]> {
const res = await fetch(`${this.baseUrl.replace(/\/$/, "")}/api/workspace-plugin/projects`, {
headers: this.headers(),
})
if (!res.ok) throw new Error(`manager listProjects failed: ${res.status} ${res.statusText}`)
const json = (await res.json()) as { projects: ManagerProject[] }
return json.projects ?? []
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { Plugin, WorkspaceAdaptor, WorkspaceInfo } from "@opencode-ai/plugin"
import { ManagerClient } from "./client.js"
import { PluginOptionsSchema, type ManagerProject } from "./types.js"
export function resolveConfig(options: unknown): { url: string; token: string } {
const parsed = PluginOptionsSchema.parse(options ?? {})
const url = parsed.url ?? process.env.OPENCODE_MANAGER_URL
const token = parsed.token ?? process.env.OPENCODE_MANAGER_TOKEN
if (!url) throw new Error("@opencode-manager/workspace-plugin: missing `url`")
if (!token) throw new Error("@opencode-manager/workspace-plugin: missing `token`")
return { url, token }
}
function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProject): WorkspaceAdaptor {
return {
name: `Manager: ${project.name}`,
description: `Connect to the "${project.name}" project on opencode-manager at ${cfg.url}`,
configure(info: WorkspaceInfo) {
return { ...info, name: project.name, directory: project.directory, extra: { slug: project.slug } }
},
async create() {},
async remove() {},
target() {
return {
type: "remote",
url: `${cfg.url.replace(/\/$/, "")}/api/opencode`,
headers: {
Authorization: `Bearer ${cfg.token}`,
"x-opencode-manager-project": project.slug,
},
}
},
}
}
export const OpencodeManagerWorkspacePlugin: Plugin = async ({ experimental_workspace }, options) => {
const cfg = resolveConfig(options)
const client = new ManagerClient(cfg.url, cfg.token)
const projects = await client.listProjects()
for (const project of projects) {
experimental_workspace.register(`manager:${project.slug}`, makeAdaptor(cfg, project))
}
return {}
}
export default OpencodeManagerWorkspacePlugin
+15
View File
@@ -0,0 +1,15 @@
import { z } from "zod"
export const PluginOptionsSchema = z.object({
url: z.string().url().optional(),
token: z.string().min(1).optional(),
})
export type PluginOptions = z.infer<typeof PluginOptionsSchema>
export type ManagerProject = {
slug: string
name: string
directory: string
description?: string
}
@@ -0,0 +1,71 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { PluginOptionsSchema } from '../src/types'
import { resolveConfig } from '../src/index'
describe('PluginOptionsSchema', () => {
it('accepts url from options', () => {
const parsed = PluginOptionsSchema.parse({ url: 'http://test.com' })
expect(parsed.url).toBe('http://test.com')
})
it('accepts token from options', () => {
const parsed = PluginOptionsSchema.parse({ token: 'test-token' })
expect(parsed.token).toBe('test-token')
})
it('requires token to be non-empty', () => {
expect(() => PluginOptionsSchema.parse({ token: '' })).toThrow()
})
it('rejects malformed url', () => {
expect(() => PluginOptionsSchema.parse({ url: 'not-a-url' })).toThrow()
})
})
describe('resolveConfig', () => {
const ORIGINAL_URL = process.env.OPENCODE_MANAGER_URL
const ORIGINAL_TOKEN = process.env.OPENCODE_MANAGER_TOKEN
beforeEach(() => {
delete process.env.OPENCODE_MANAGER_URL
delete process.env.OPENCODE_MANAGER_TOKEN
})
afterEach(() => {
if (ORIGINAL_URL === undefined) delete process.env.OPENCODE_MANAGER_URL
else process.env.OPENCODE_MANAGER_URL = ORIGINAL_URL
if (ORIGINAL_TOKEN === undefined) delete process.env.OPENCODE_MANAGER_TOKEN
else process.env.OPENCODE_MANAGER_TOKEN = ORIGINAL_TOKEN
})
it('uses options when provided', () => {
const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' })
expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' })
})
it('falls back to env vars when options omit fields', () => {
process.env.OPENCODE_MANAGER_URL = 'http://env.com'
process.env.OPENCODE_MANAGER_TOKEN = 'env-token'
const cfg = resolveConfig({})
expect(cfg).toEqual({ url: 'http://env.com', token: 'env-token' })
})
it('prefers options over env vars when both present', () => {
process.env.OPENCODE_MANAGER_URL = 'http://env.com'
process.env.OPENCODE_MANAGER_TOKEN = 'env-token'
const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' })
expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' })
})
it('throws when url missing from both options and env', () => {
process.env.OPENCODE_MANAGER_TOKEN = 'env-token'
expect(() => resolveConfig({})).toThrow(/missing `url`/)
})
it('throws when token missing from both options and env', () => {
process.env.OPENCODE_MANAGER_URL = 'http://env.com'
expect(() => resolveConfig({})).toThrow(/missing `token`/)
})
})
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"noEmit": true,
"lib": ["ES2022"]
},
"include": ["src/**/*", "test/**/*"],
"exclude": ["node_modules"]
}
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
},
})