@pixelbyte-software/pixcode 1.33.7 → 1.33.8

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.
Files changed (34) hide show
  1. package/dist/assets/{index-BQizjYZ6.js → index-JU38YIxa.js} +138 -138
  2. package/dist/favicon.svg +8 -8
  3. package/dist/icons/icon-128x128.svg +9 -9
  4. package/dist/icons/icon-144x144.svg +9 -9
  5. package/dist/icons/icon-152x152.svg +9 -9
  6. package/dist/icons/icon-192x192.svg +9 -9
  7. package/dist/icons/icon-384x384.svg +9 -9
  8. package/dist/icons/icon-512x512.svg +9 -9
  9. package/dist/icons/icon-72x72.svg +9 -9
  10. package/dist/icons/icon-96x96.svg +9 -9
  11. package/dist/icons/icon-template.svg +9 -9
  12. package/dist/index.html +1 -1
  13. package/dist/logo.svg +12 -12
  14. package/package.json +1 -1
  15. package/server/database/db.js +794 -794
  16. package/server/database/json-store.js +194 -194
  17. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  18. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  19. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +193 -193
  20. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  21. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  22. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  23. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +218 -218
  24. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  25. package/server/modules/providers/shared/provider-configs.ts +142 -142
  26. package/server/qwen-code-cli.js +395 -395
  27. package/server/qwen-response-handler.js +73 -73
  28. package/server/routes/qwen.js +27 -27
  29. package/server/services/external-access.js +171 -171
  30. package/server/services/provider-credentials.js +155 -155
  31. package/server/services/provider-models.js +381 -381
  32. package/server/services/telegram/telegram-http-client.js +130 -130
  33. package/server/services/vapid-keys.js +36 -36
  34. package/server/utils/port-access.js +209 -209
@@ -1,194 +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();
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();
@@ -1,130 +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
- }
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
+ }