@pixelbyte-software/pixcode 1.31.13 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/index-Byb8Wnts.css +32 -0
- package/dist/assets/{index-oxZnRcf8.js → index-CZKV8Tbj.js} +163 -151
- package/dist/index.html +2 -2
- package/dist-server/server/database/db.js +542 -460
- package/dist-server/server/database/db.js.map +1 -1
- package/dist-server/server/database/json-store.js +184 -0
- package/dist-server/server/database/json-store.js.map +1 -0
- package/dist-server/server/index.js +16 -1
- package/dist-server/server/index.js.map +1 -1
- package/dist-server/server/modules/providers/list/opencode/opencode-auth.provider.js +113 -0
- package/dist-server/server/modules/providers/list/opencode/opencode-auth.provider.js.map +1 -0
- package/dist-server/server/modules/providers/list/opencode/opencode-mcp.provider.js +98 -0
- package/dist-server/server/modules/providers/list/opencode/opencode-mcp.provider.js.map +1 -0
- package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +138 -0
- package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js.map +1 -0
- package/dist-server/server/modules/providers/list/opencode/opencode.provider.js +27 -0
- package/dist-server/server/modules/providers/list/opencode/opencode.provider.js.map +1 -0
- package/dist-server/server/modules/providers/provider.registry.js +2 -0
- package/dist-server/server/modules/providers/provider.registry.js.map +1 -1
- package/dist-server/server/modules/providers/provider.routes.js +4 -1
- package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
- package/dist-server/server/modules/providers/shared/provider-configs.js +24 -0
- package/dist-server/server/modules/providers/shared/provider-configs.js.map +1 -1
- package/dist-server/server/routes/auth.js +5 -1
- package/dist-server/server/routes/auth.js.map +1 -1
- package/dist-server/server/routes/network.js +14 -21
- package/dist-server/server/routes/network.js.map +1 -1
- package/dist-server/server/services/external-access.js +18 -78
- package/dist-server/server/services/external-access.js.map +1 -1
- package/dist-server/server/services/install-jobs.js +2 -0
- package/dist-server/server/services/install-jobs.js.map +1 -1
- package/dist-server/server/services/provider-credentials.js +4 -0
- package/dist-server/server/services/provider-credentials.js.map +1 -1
- package/dist-server/server/services/telegram/bot.js +6 -6
- package/dist-server/server/services/telegram/bot.js.map +1 -1
- package/dist-server/server/services/telegram/telegram-http-client.js +130 -0
- package/dist-server/server/services/telegram/telegram-http-client.js.map +1 -0
- package/dist-server/server/services/vapid-keys.js +3 -3
- package/dist-server/server/services/vapid-keys.js.map +1 -1
- package/dist-server/shared/modelConstants.js +20 -0
- package/dist-server/shared/modelConstants.js.map +1 -1
- package/package.json +178 -178
- package/server/database/db.js +794 -696
- package/server/database/json-store.js +194 -0
- package/server/index.js +14 -1
- package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -0
- package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -0
- package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +155 -0
- package/server/modules/providers/list/opencode/opencode.provider.ts +29 -0
- package/server/modules/providers/provider.registry.ts +2 -0
- package/server/modules/providers/provider.routes.ts +4 -0
- package/server/modules/providers/shared/provider-configs.ts +24 -0
- package/server/routes/auth.js +5 -1
- package/server/routes/network.js +13 -21
- package/server/services/external-access.js +171 -240
- package/server/services/install-jobs.js +2 -0
- package/server/services/provider-credentials.js +8 -4
- package/server/services/telegram/bot.js +6 -7
- package/server/services/telegram/telegram-http-client.js +130 -0
- package/server/services/vapid-keys.js +36 -35
- package/server/shared/types.ts +1 -1
- package/shared/modelConstants.js +22 -0
- package/dist/assets/index-CLxSMbv1.css +0 -32
- package/dist-server/server/database/schema.js +0 -130
- package/dist-server/server/database/schema.js.map +0 -1
- package/server/database/schema.js +0 -138
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Minimal JSON-backed store with atomic writes.
|
|
6
|
+
*
|
|
7
|
+
* Replaces the `better-sqlite3` auth/session/telegram DB from previous
|
|
8
|
+
* releases. The backing store is kilobytes, not gigabytes — a SQL engine
|
|
9
|
+
* was overkill and the native compile dragged install-time warnings +
|
|
10
|
+
* on-disk WAL files that confused users. This impl:
|
|
11
|
+
*
|
|
12
|
+
* - Loads the entire store into memory on first access (synchronous
|
|
13
|
+
* readFileSync) and keeps it cached; all subsequent reads hit the
|
|
14
|
+
* in-memory structure.
|
|
15
|
+
* - Every write flushes the whole document via write-to-tmp + rename
|
|
16
|
+
* so a crash mid-write can never truncate the file; either the
|
|
17
|
+
* old file survives or the new one is fully written.
|
|
18
|
+
* - All operations are synchronous and rely on Node's single-threaded
|
|
19
|
+
* JS execution for concurrency safety. No async queue, no locks.
|
|
20
|
+
*
|
|
21
|
+
* The schema is a flat object with one array per "table":
|
|
22
|
+
* { _version, _sequences: {<table>: nextId}, users: [...], ... }
|
|
23
|
+
*
|
|
24
|
+
* Callers use helpers like `insert`, `updateWhere`, `findWhere`,
|
|
25
|
+
* `deleteWhere` rather than composing queries — this is a key/value map
|
|
26
|
+
* with filter helpers, not a SQL engine.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const CURRENT_VERSION = 1;
|
|
30
|
+
|
|
31
|
+
// Tables the store manages — empty arrays on a fresh file.
|
|
32
|
+
const EMPTY_STORE = () => ({
|
|
33
|
+
_version: CURRENT_VERSION,
|
|
34
|
+
_sequences: {
|
|
35
|
+
users: 0,
|
|
36
|
+
api_keys: 0,
|
|
37
|
+
user_credentials: 0,
|
|
38
|
+
vapid_keys: 0,
|
|
39
|
+
push_subscriptions: 0,
|
|
40
|
+
},
|
|
41
|
+
users: [],
|
|
42
|
+
api_keys: [],
|
|
43
|
+
user_credentials: [],
|
|
44
|
+
user_notification_preferences: [], // each row: { user_id, preferences_json, updated_at }
|
|
45
|
+
vapid_keys: [],
|
|
46
|
+
push_subscriptions: [],
|
|
47
|
+
session_names: [], // each row: { session_id, provider, custom_name, created_at, updated_at }
|
|
48
|
+
app_config: [], // each row: { key, value, created_at }
|
|
49
|
+
telegram_config: [], // 0 or 1 row: { id=1, bot_token, bot_username, updated_at }
|
|
50
|
+
telegram_links: [], // each row: { user_id, chat_id, ... }
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
export class JsonStore {
|
|
54
|
+
constructor(filePath) {
|
|
55
|
+
this.filePath = filePath;
|
|
56
|
+
this.tmpPath = `${filePath}.tmp`;
|
|
57
|
+
this.data = null;
|
|
58
|
+
this._ensureLoaded();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
_ensureLoaded() {
|
|
62
|
+
if (this.data) return;
|
|
63
|
+
|
|
64
|
+
// Ensure parent directory exists — matches the old better-sqlite3
|
|
65
|
+
// behavior where the directory was created during initialization.
|
|
66
|
+
const dir = path.dirname(this.filePath);
|
|
67
|
+
if (!fs.existsSync(dir)) {
|
|
68
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!fs.existsSync(this.filePath)) {
|
|
72
|
+
this.data = EMPTY_STORE();
|
|
73
|
+
this._flush();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
const raw = fs.readFileSync(this.filePath, 'utf8');
|
|
79
|
+
const parsed = JSON.parse(raw);
|
|
80
|
+
// Fill missing keys from EMPTY_STORE so adding a new "table" in a
|
|
81
|
+
// later schema doesn't crash a fresh deploy reading an old file.
|
|
82
|
+
this.data = { ...EMPTY_STORE(), ...parsed };
|
|
83
|
+
// Ensure each well-known array key is actually an array — defends
|
|
84
|
+
// against a hand-edited file that set one to null or an object.
|
|
85
|
+
const empty = EMPTY_STORE();
|
|
86
|
+
for (const key of Object.keys(empty)) {
|
|
87
|
+
if (key === '_version' || key === '_sequences') continue;
|
|
88
|
+
if (!Array.isArray(this.data[key])) {
|
|
89
|
+
this.data[key] = [];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
this.data._sequences = { ...empty._sequences, ...(parsed._sequences || {}) };
|
|
93
|
+
} catch (err) {
|
|
94
|
+
// Corrupted file — back up and start fresh. Never hide this; it's
|
|
95
|
+
// very likely user-visible (logins will reset).
|
|
96
|
+
const backup = `${this.filePath}.corrupt-${Date.now()}`;
|
|
97
|
+
console.error(`[JsonStore] Failed to read ${this.filePath}: ${err.message}. Backing up to ${backup}.`);
|
|
98
|
+
try { fs.renameSync(this.filePath, backup); } catch { /* noop */ }
|
|
99
|
+
this.data = EMPTY_STORE();
|
|
100
|
+
this._flush();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
_flush() {
|
|
105
|
+
const serialized = JSON.stringify(this.data, null, 2);
|
|
106
|
+
fs.writeFileSync(this.tmpPath, serialized, 'utf8');
|
|
107
|
+
fs.renameSync(this.tmpPath, this.filePath);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------- Raw access ----------
|
|
111
|
+
get raw() {
|
|
112
|
+
this._ensureLoaded();
|
|
113
|
+
return this.data;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
save() { this._flush(); }
|
|
117
|
+
|
|
118
|
+
// ---------- Sequence (AUTOINCREMENT) ----------
|
|
119
|
+
nextId(table) {
|
|
120
|
+
this._ensureLoaded();
|
|
121
|
+
this.data._sequences[table] = (this.data._sequences[table] || 0) + 1;
|
|
122
|
+
return this.data._sequences[table];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---------- Query helpers ----------
|
|
126
|
+
findWhere(table, predicate) {
|
|
127
|
+
this._ensureLoaded();
|
|
128
|
+
return this.data[table].find(predicate) || null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
filterWhere(table, predicate) {
|
|
132
|
+
this._ensureLoaded();
|
|
133
|
+
return this.data[table].filter(predicate);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
count(table, predicate) {
|
|
137
|
+
this._ensureLoaded();
|
|
138
|
+
if (!predicate) return this.data[table].length;
|
|
139
|
+
return this.data[table].filter(predicate).length;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---------- Mutation helpers ----------
|
|
143
|
+
insert(table, row, { autoId = true, sequenceKey } = {}) {
|
|
144
|
+
this._ensureLoaded();
|
|
145
|
+
const finalRow = { ...row };
|
|
146
|
+
if (autoId && finalRow.id === undefined) {
|
|
147
|
+
finalRow.id = this.nextId(sequenceKey || table);
|
|
148
|
+
}
|
|
149
|
+
this.data[table].push(finalRow);
|
|
150
|
+
this._flush();
|
|
151
|
+
return finalRow;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
updateWhere(table, predicate, updater) {
|
|
155
|
+
this._ensureLoaded();
|
|
156
|
+
let changed = 0;
|
|
157
|
+
for (const row of this.data[table]) {
|
|
158
|
+
if (predicate(row)) {
|
|
159
|
+
const patch = typeof updater === 'function' ? updater(row) : updater;
|
|
160
|
+
Object.assign(row, patch);
|
|
161
|
+
changed += 1;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (changed > 0) this._flush();
|
|
165
|
+
return changed;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
upsertWhere(table, predicate, row) {
|
|
169
|
+
this._ensureLoaded();
|
|
170
|
+
const existing = this.data[table].find(predicate);
|
|
171
|
+
if (existing) {
|
|
172
|
+
Object.assign(existing, row);
|
|
173
|
+
this._flush();
|
|
174
|
+
return existing;
|
|
175
|
+
}
|
|
176
|
+
return this.insert(table, row);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
deleteWhere(table, predicate) {
|
|
180
|
+
this._ensureLoaded();
|
|
181
|
+
const before = this.data[table].length;
|
|
182
|
+
this.data[table] = this.data[table].filter((row) => !predicate(row));
|
|
183
|
+
const removed = before - this.data[table].length;
|
|
184
|
+
if (removed > 0) this._flush();
|
|
185
|
+
return removed;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Helper — ISO timestamp matching the DATETIME format SQLite used to
|
|
191
|
+
* write. Stored as a plain ISO string; no one actually parses it beyond
|
|
192
|
+
* displaying "last login X hours ago".
|
|
193
|
+
*/
|
|
194
|
+
export const nowIso = () => new Date().toISOString();
|
package/server/index.js
CHANGED
|
@@ -90,7 +90,7 @@ import { IS_PLATFORM } from './constants/config.js';
|
|
|
90
90
|
import { getConnectableHost } from '../shared/networkHosts.js';
|
|
91
91
|
import { buildDaemonCliCommand, handleDaemonCommand } from './daemon-manager.js';
|
|
92
92
|
|
|
93
|
-
const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini', 'qwen'];
|
|
93
|
+
const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini', 'qwen', 'opencode'];
|
|
94
94
|
|
|
95
95
|
// File system watchers for provider project/session folders
|
|
96
96
|
const PROVIDER_WATCH_PATHS = [
|
|
@@ -2070,6 +2070,19 @@ function handleShellConnection(ws) {
|
|
|
2070
2070
|
} else {
|
|
2071
2071
|
shellCommand = command;
|
|
2072
2072
|
}
|
|
2073
|
+
} else if (provider === 'opencode') {
|
|
2074
|
+
// OpenCode uses `--session <id>` for resumption per the
|
|
2075
|
+
// 2026 CLI docs. The session IDs the TUI creates match
|
|
2076
|
+
// our `safeSessionIdPattern` regex (ulid/nanoid), so
|
|
2077
|
+
// we pass them straight through without a cliSessionId
|
|
2078
|
+
// mapping layer — OpenCode doesn't renumber IDs the way
|
|
2079
|
+
// Gemini does.
|
|
2080
|
+
const command = initialCommand || 'opencode';
|
|
2081
|
+
if (hasSession && sessionId && safeSessionIdPattern.test(sessionId)) {
|
|
2082
|
+
shellCommand = `${command} --session "${sessionId}"`;
|
|
2083
|
+
} else {
|
|
2084
|
+
shellCommand = command;
|
|
2085
|
+
}
|
|
2073
2086
|
} else {
|
|
2074
2087
|
// Claude (default provider)
|
|
2075
2088
|
const command = initialCommand || 'claude';
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import spawn from 'cross-spawn';
|
|
6
|
+
|
|
7
|
+
import type { IProviderAuth } from '@/shared/interfaces.js';
|
|
8
|
+
import type { ProviderAuthStatus } from '@/shared/types.js';
|
|
9
|
+
import { readObjectRecord, readOptionalString } from '@/shared/utils.js';
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
11
|
+
// @ts-ignore — plain-JS module, typed via inference
|
|
12
|
+
import { getProviderCredentials } from '@/services/provider-credentials.js';
|
|
13
|
+
|
|
14
|
+
type OpencodeCredentialsStatus = {
|
|
15
|
+
authenticated: boolean;
|
|
16
|
+
email: string | null;
|
|
17
|
+
method: string | null;
|
|
18
|
+
error?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* OpenCode auth checker.
|
|
23
|
+
*
|
|
24
|
+
* OpenCode stores credentials at `~/.local/share/opencode/auth.json` (XDG
|
|
25
|
+
* data dir — different layout from the other providers which use
|
|
26
|
+
* `~/.<name>/`). The file is a JSON map of `providerName → { type, ... }`
|
|
27
|
+
* where type is `api` (API key), `oauth` (OAuth tokens), or similar.
|
|
28
|
+
*
|
|
29
|
+
* Windows layout (as of the 2026 release): `%LOCALAPPDATA%\opencode\auth.json`.
|
|
30
|
+
*
|
|
31
|
+
* Since OpenCode is multi-provider (OpenAI, Anthropic, Google, Ollama,
|
|
32
|
+
* OpenCode Zen), "authenticated" here means "at least ONE provider in
|
|
33
|
+
* auth.json has credentials" — we don't care which.
|
|
34
|
+
*/
|
|
35
|
+
export class OpencodeProviderAuth implements IProviderAuth {
|
|
36
|
+
private checkInstalled(): boolean {
|
|
37
|
+
const cliPath = process.env.OPENCODE_CLI_PATH || 'opencode';
|
|
38
|
+
try {
|
|
39
|
+
const result = spawn.sync(cliPath, ['--version'], { stdio: 'ignore', timeout: 5000 });
|
|
40
|
+
return !result.error && result.status === 0;
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async getStatus(): Promise<ProviderAuthStatus> {
|
|
47
|
+
const installed = this.checkInstalled();
|
|
48
|
+
|
|
49
|
+
if (!installed) {
|
|
50
|
+
return {
|
|
51
|
+
installed,
|
|
52
|
+
provider: 'opencode',
|
|
53
|
+
authenticated: false,
|
|
54
|
+
email: null,
|
|
55
|
+
method: null,
|
|
56
|
+
error: 'OpenCode CLI is not installed',
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const credentials = await this.checkCredentials();
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
installed,
|
|
64
|
+
provider: 'opencode',
|
|
65
|
+
authenticated: credentials.authenticated,
|
|
66
|
+
email: credentials.email,
|
|
67
|
+
method: credentials.method,
|
|
68
|
+
error: credentials.authenticated ? undefined : credentials.error || 'Not authenticated',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private async checkCredentials(): Promise<OpencodeCredentialsStatus> {
|
|
73
|
+
// Pixcode-managed credentials come first — if the user stored an API
|
|
74
|
+
// key via Settings > Agents > API Key, trust that regardless of
|
|
75
|
+
// env vars or auth.json.
|
|
76
|
+
try {
|
|
77
|
+
const creds = await getProviderCredentials('opencode');
|
|
78
|
+
if (creds?.apiKey) {
|
|
79
|
+
return { authenticated: true, email: 'API Key Auth', method: 'pixcode_store' };
|
|
80
|
+
}
|
|
81
|
+
} catch { /* fall through */ }
|
|
82
|
+
|
|
83
|
+
// Env-var shortcut — any of the multi-provider keys OpenCode recognises.
|
|
84
|
+
const envKeys = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GOOGLE_API_KEY', 'OPENROUTER_API_KEY'];
|
|
85
|
+
for (const k of envKeys) {
|
|
86
|
+
if (process.env[k]?.trim()) {
|
|
87
|
+
return { authenticated: true, email: `${k.replace('_API_KEY', '')} env`, method: 'api_key' };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// auth.json — written by `opencode auth login`. On Windows the XDG
|
|
92
|
+
// data dir typically resolves to `%LOCALAPPDATA%\opencode`, but since
|
|
93
|
+
// Node's `os.homedir()` + `.local/share/opencode` covers the Linux
|
|
94
|
+
// default and most WSL cases, we check both paths.
|
|
95
|
+
const candidatePaths = [
|
|
96
|
+
path.join(os.homedir(), '.local', 'share', 'opencode', 'auth.json'),
|
|
97
|
+
path.join(os.homedir(), 'AppData', 'Local', 'opencode', 'auth.json'),
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
for (const credsPath of candidatePaths) {
|
|
101
|
+
try {
|
|
102
|
+
const content = await readFile(credsPath, 'utf8');
|
|
103
|
+
const creds = readObjectRecord(JSON.parse(content)) ?? {};
|
|
104
|
+
const providerNames = Object.keys(creds);
|
|
105
|
+
if (providerNames.length > 0) {
|
|
106
|
+
// Prefer a real provider label over a generic one when we can
|
|
107
|
+
// identify it.
|
|
108
|
+
const firstProvider = providerNames[0];
|
|
109
|
+
const firstConfig = readObjectRecord(creds[firstProvider]) ?? {};
|
|
110
|
+
const authType = readOptionalString(firstConfig.type) ?? 'stored';
|
|
111
|
+
const label = providerNames.length === 1
|
|
112
|
+
? `${firstProvider} (${authType})`
|
|
113
|
+
: `${providerNames.length} providers configured`;
|
|
114
|
+
return {
|
|
115
|
+
authenticated: true,
|
|
116
|
+
email: label,
|
|
117
|
+
method: authType === 'oauth' ? 'credentials_file' : 'api_key',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
} catch { /* try next path */ }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
authenticated: false,
|
|
125
|
+
email: null,
|
|
126
|
+
method: null,
|
|
127
|
+
error: 'OpenCode is not configured — run `opencode auth login`.',
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { McpProvider } from '@/modules/providers/shared/mcp/mcp.provider.js';
|
|
5
|
+
import type { McpScope, ProviderMcpServer, UpsertProviderMcpServerInput } from '@/shared/types.js';
|
|
6
|
+
import {
|
|
7
|
+
AppError,
|
|
8
|
+
readJsonConfig,
|
|
9
|
+
readObjectRecord,
|
|
10
|
+
readOptionalString,
|
|
11
|
+
readStringArray,
|
|
12
|
+
readStringRecord,
|
|
13
|
+
writeJsonConfig,
|
|
14
|
+
} from '@/shared/utils.js';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* OpenCode MCP provider.
|
|
18
|
+
*
|
|
19
|
+
* OpenCode's MCP servers live under the top-level `mcp` key in
|
|
20
|
+
* `opencode.json` (global at `~/.config/opencode/opencode.json`, project at
|
|
21
|
+
* `<workspace>/opencode.json`). Each entry is either a local stdio command
|
|
22
|
+
* (`{ command, args, env }`) or a remote server (`{ type: "remote", url,
|
|
23
|
+
* headers, enabled }`). OpenCode's schema also supports an `enabled: false`
|
|
24
|
+
* flag we preserve on write but don't surface in the UI yet.
|
|
25
|
+
*/
|
|
26
|
+
export class OpencodeMcpProvider extends McpProvider {
|
|
27
|
+
constructor() {
|
|
28
|
+
super('opencode', ['user', 'project'], ['stdio', 'http', 'sse']);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
protected async readScopedServers(scope: McpScope, workspacePath: string): Promise<Record<string, unknown>> {
|
|
32
|
+
const filePath = scope === 'user'
|
|
33
|
+
? path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
|
|
34
|
+
: path.join(workspacePath, 'opencode.json');
|
|
35
|
+
const config = await readJsonConfig(filePath);
|
|
36
|
+
return readObjectRecord(config.mcp) ?? {};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
protected async writeScopedServers(
|
|
40
|
+
scope: McpScope,
|
|
41
|
+
workspacePath: string,
|
|
42
|
+
servers: Record<string, unknown>,
|
|
43
|
+
): Promise<void> {
|
|
44
|
+
const filePath = scope === 'user'
|
|
45
|
+
? path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
|
|
46
|
+
: path.join(workspacePath, 'opencode.json');
|
|
47
|
+
const config = await readJsonConfig(filePath);
|
|
48
|
+
config.mcp = servers;
|
|
49
|
+
await writeJsonConfig(filePath, config);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
protected buildServerConfig(input: UpsertProviderMcpServerInput): Record<string, unknown> {
|
|
53
|
+
if (input.transport === 'stdio') {
|
|
54
|
+
if (!input.command?.trim()) {
|
|
55
|
+
throw new AppError('command is required for stdio MCP servers.', {
|
|
56
|
+
code: 'MCP_COMMAND_REQUIRED',
|
|
57
|
+
statusCode: 400,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
type: 'local',
|
|
62
|
+
command: input.command,
|
|
63
|
+
args: input.args ?? [],
|
|
64
|
+
env: input.env ?? {},
|
|
65
|
+
cwd: input.cwd,
|
|
66
|
+
enabled: true,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!input.url?.trim()) {
|
|
71
|
+
throw new AppError('url is required for http/sse MCP servers.', {
|
|
72
|
+
code: 'MCP_URL_REQUIRED',
|
|
73
|
+
statusCode: 400,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
type: 'remote',
|
|
79
|
+
url: input.url,
|
|
80
|
+
headers: input.headers ?? {},
|
|
81
|
+
enabled: true,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
protected normalizeServerConfig(
|
|
86
|
+
scope: McpScope,
|
|
87
|
+
name: string,
|
|
88
|
+
rawConfig: unknown,
|
|
89
|
+
): ProviderMcpServer | null {
|
|
90
|
+
if (!rawConfig || typeof rawConfig !== 'object') {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const config = rawConfig as Record<string, unknown>;
|
|
95
|
+
const opencodeType = readOptionalString(config.type);
|
|
96
|
+
|
|
97
|
+
// Local (stdio) entries — either type: "local" explicitly or any entry
|
|
98
|
+
// with a command field (pre-type schemas).
|
|
99
|
+
if (opencodeType === 'local' || typeof config.command === 'string') {
|
|
100
|
+
return {
|
|
101
|
+
provider: 'opencode',
|
|
102
|
+
name,
|
|
103
|
+
scope,
|
|
104
|
+
transport: 'stdio',
|
|
105
|
+
command: typeof config.command === 'string' ? config.command : '',
|
|
106
|
+
args: readStringArray(config.args),
|
|
107
|
+
env: readStringRecord(config.env),
|
|
108
|
+
cwd: readOptionalString(config.cwd),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Remote entries — type: "remote" or any entry with a url field.
|
|
113
|
+
if (opencodeType === 'remote' || typeof config.url === 'string') {
|
|
114
|
+
return {
|
|
115
|
+
provider: 'opencode',
|
|
116
|
+
name,
|
|
117
|
+
scope,
|
|
118
|
+
transport: 'http',
|
|
119
|
+
url: typeof config.url === 'string' ? config.url : '',
|
|
120
|
+
headers: readStringRecord(config.headers),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import sessionManager from '@/sessionManager.js';
|
|
2
|
+
import type { IProviderSessions } from '@/shared/interfaces.js';
|
|
3
|
+
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
|
4
|
+
import { createNormalizedMessage, generateMessageId, readObjectRecord } from '@/shared/utils.js';
|
|
5
|
+
|
|
6
|
+
const PROVIDER = 'opencode';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* OpenCode sessions provider.
|
|
10
|
+
*
|
|
11
|
+
* OpenCode persists session transcripts under
|
|
12
|
+
* `~/.local/share/opencode/project/<project-slug>/sessions/` (XDG data dir).
|
|
13
|
+
* The on-disk format is JSON per session — different from Gemini/Qwen's
|
|
14
|
+
* single-file-per-conversation layout. For the initial integration we
|
|
15
|
+
* read transcripts only from the in-memory sessionManager (freshly
|
|
16
|
+
* captured streams); restoring historical sessions from disk will land
|
|
17
|
+
* in a follow-up once the exact schema is pinned.
|
|
18
|
+
*
|
|
19
|
+
* Stream events follow the headless `opencode serve` API contract —
|
|
20
|
+
* messages carry `{ role, parts: [{ type: text|tool-use|tool-result, ... }] }`.
|
|
21
|
+
*/
|
|
22
|
+
export class OpencodeSessionsProvider implements IProviderSessions {
|
|
23
|
+
normalizeMessage(rawMessage: unknown, sessionId: string | null): NormalizedMessage[] {
|
|
24
|
+
const raw = readObjectRecord(rawMessage);
|
|
25
|
+
if (!raw) return [];
|
|
26
|
+
|
|
27
|
+
const ts = raw.timestamp || new Date().toISOString();
|
|
28
|
+
const baseId = raw.uuid || raw.id || generateMessageId('opencode');
|
|
29
|
+
|
|
30
|
+
if (raw.type === 'message' && raw.role === 'assistant') {
|
|
31
|
+
const content = raw.content || '';
|
|
32
|
+
const messages: NormalizedMessage[] = [];
|
|
33
|
+
if (content) {
|
|
34
|
+
messages.push(createNormalizedMessage({
|
|
35
|
+
id: baseId,
|
|
36
|
+
sessionId,
|
|
37
|
+
timestamp: ts,
|
|
38
|
+
provider: PROVIDER,
|
|
39
|
+
kind: 'stream_delta',
|
|
40
|
+
content,
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
if (raw.delta !== true) {
|
|
44
|
+
messages.push(createNormalizedMessage({
|
|
45
|
+
sessionId,
|
|
46
|
+
timestamp: ts,
|
|
47
|
+
provider: PROVIDER,
|
|
48
|
+
kind: 'stream_end',
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
return messages;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (raw.type === 'tool_use' || raw.type === 'tool-use') {
|
|
55
|
+
return [createNormalizedMessage({
|
|
56
|
+
id: baseId,
|
|
57
|
+
sessionId,
|
|
58
|
+
timestamp: ts,
|
|
59
|
+
provider: PROVIDER,
|
|
60
|
+
kind: 'tool_use',
|
|
61
|
+
toolName: raw.tool_name || raw.name,
|
|
62
|
+
toolInput: raw.parameters || raw.input || {},
|
|
63
|
+
toolId: raw.tool_id || raw.id || baseId,
|
|
64
|
+
})];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (raw.type === 'tool_result' || raw.type === 'tool-result') {
|
|
68
|
+
return [createNormalizedMessage({
|
|
69
|
+
id: baseId,
|
|
70
|
+
sessionId,
|
|
71
|
+
timestamp: ts,
|
|
72
|
+
provider: PROVIDER,
|
|
73
|
+
kind: 'tool_result',
|
|
74
|
+
toolId: raw.tool_id || raw.toolCallId || '',
|
|
75
|
+
content: raw.output === undefined ? '' : String(raw.output),
|
|
76
|
+
isError: raw.status === 'error' || Boolean(raw.isError),
|
|
77
|
+
})];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (raw.type === 'result') {
|
|
81
|
+
return [createNormalizedMessage({
|
|
82
|
+
sessionId,
|
|
83
|
+
timestamp: ts,
|
|
84
|
+
provider: PROVIDER,
|
|
85
|
+
kind: 'stream_end',
|
|
86
|
+
})];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (raw.type === 'error') {
|
|
90
|
+
return [createNormalizedMessage({
|
|
91
|
+
id: baseId,
|
|
92
|
+
sessionId,
|
|
93
|
+
timestamp: ts,
|
|
94
|
+
provider: PROVIDER,
|
|
95
|
+
kind: 'error',
|
|
96
|
+
content: raw.error || raw.message || 'Unknown OpenCode streaming error',
|
|
97
|
+
})];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async fetchHistory(
|
|
104
|
+
sessionId: string,
|
|
105
|
+
options: FetchHistoryOptions = {},
|
|
106
|
+
): Promise<FetchHistoryResult> {
|
|
107
|
+
const { limit = null, offset = 0 } = options;
|
|
108
|
+
|
|
109
|
+
let rawMessages: AnyRecord[] = [];
|
|
110
|
+
try {
|
|
111
|
+
rawMessages = sessionManager.getSessionMessages(sessionId) as AnyRecord[];
|
|
112
|
+
} catch (error) {
|
|
113
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
114
|
+
console.warn(`[OpencodeProvider] Failed to load session ${sessionId}:`, message);
|
|
115
|
+
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const normalized: NormalizedMessage[] = [];
|
|
119
|
+
for (const raw of rawMessages) {
|
|
120
|
+
const ts = raw.timestamp || new Date().toISOString();
|
|
121
|
+
const baseId = raw.uuid || raw.id || generateMessageId('opencode');
|
|
122
|
+
const role = raw.message?.role || raw.role;
|
|
123
|
+
const content = raw.message?.content || raw.content;
|
|
124
|
+
|
|
125
|
+
if (!role || !content) continue;
|
|
126
|
+
const normalizedRole = role === 'user' ? 'user' : 'assistant';
|
|
127
|
+
|
|
128
|
+
if (typeof content === 'string' && content.trim()) {
|
|
129
|
+
normalized.push(createNormalizedMessage({
|
|
130
|
+
id: baseId,
|
|
131
|
+
sessionId,
|
|
132
|
+
timestamp: ts,
|
|
133
|
+
provider: PROVIDER,
|
|
134
|
+
kind: 'text',
|
|
135
|
+
role: normalizedRole,
|
|
136
|
+
content,
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const start = Math.max(0, offset);
|
|
142
|
+
const pageLimit = limit === null ? null : Math.max(0, limit);
|
|
143
|
+
const messages = pageLimit === null
|
|
144
|
+
? normalized.slice(start)
|
|
145
|
+
: normalized.slice(start, start + pageLimit);
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
messages,
|
|
149
|
+
total: normalized.length,
|
|
150
|
+
hasMore: pageLimit === null ? false : start + pageLimit < normalized.length,
|
|
151
|
+
offset: start,
|
|
152
|
+
limit: pageLimit,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { AbstractProvider } from '@/modules/providers/shared/base/abstract.provider.js';
|
|
2
|
+
import { OpencodeProviderAuth } from '@/modules/providers/list/opencode/opencode-auth.provider.js';
|
|
3
|
+
import { OpencodeMcpProvider } from '@/modules/providers/list/opencode/opencode-mcp.provider.js';
|
|
4
|
+
import { OpencodeSessionsProvider } from '@/modules/providers/list/opencode/opencode-sessions.provider.js';
|
|
5
|
+
import type { IProviderAuth, IProviderSessions } from '@/shared/interfaces.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* OpenCode provider.
|
|
9
|
+
*
|
|
10
|
+
* OpenCode (npm package: `opencode-ai`, binary: `opencode`) is a
|
|
11
|
+
* multi-provider terminal coding agent. Unlike Claude/Codex/Gemini/Qwen
|
|
12
|
+
* it uses XDG paths:
|
|
13
|
+
* - config: `~/.config/opencode/opencode.json`
|
|
14
|
+
* - data: `~/.local/share/opencode/` (auth.json, sessions, logs)
|
|
15
|
+
*
|
|
16
|
+
* Its permission system is granular (per-tool + per-pattern) rather than
|
|
17
|
+
* the 2/3-mode toggle other CLIs expose. We surface that through the
|
|
18
|
+
* Configuration tab and the opencode.json editor — the Permissions tab
|
|
19
|
+
* exposes high-level presets only.
|
|
20
|
+
*/
|
|
21
|
+
export class OpencodeProvider extends AbstractProvider {
|
|
22
|
+
readonly mcp = new OpencodeMcpProvider();
|
|
23
|
+
readonly auth: IProviderAuth = new OpencodeProviderAuth();
|
|
24
|
+
readonly sessions: IProviderSessions = new OpencodeSessionsProvider();
|
|
25
|
+
|
|
26
|
+
constructor() {
|
|
27
|
+
super('opencode');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -2,6 +2,7 @@ import { ClaudeProvider } from '@/modules/providers/list/claude/claude.provider.
|
|
|
2
2
|
import { CodexProvider } from '@/modules/providers/list/codex/codex.provider.js';
|
|
3
3
|
import { CursorProvider } from '@/modules/providers/list/cursor/cursor.provider.js';
|
|
4
4
|
import { GeminiProvider } from '@/modules/providers/list/gemini/gemini.provider.js';
|
|
5
|
+
import { OpencodeProvider } from '@/modules/providers/list/opencode/opencode.provider.js';
|
|
5
6
|
import { QwenProvider } from '@/modules/providers/list/qwen/qwen.provider.js';
|
|
6
7
|
import type { IProvider } from '@/shared/interfaces.js';
|
|
7
8
|
import type { LLMProvider } from '@/shared/types.js';
|
|
@@ -13,6 +14,7 @@ const providers: Record<LLMProvider, IProvider> = {
|
|
|
13
14
|
cursor: new CursorProvider(),
|
|
14
15
|
gemini: new GeminiProvider(),
|
|
15
16
|
qwen: new QwenProvider(),
|
|
17
|
+
opencode: new OpencodeProvider(),
|
|
16
18
|
};
|
|
17
19
|
|
|
18
20
|
/**
|