@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,126 +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
- }
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
+ }
@@ -1,193 +1,193 @@
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
- // OpenCode `--format json` emits errors as
91
- // { type:"error", error:{ name, data:{ message, statusCode?, isRetryable? } } }
92
- // — `error` is always an object wrapper, never a plain string. Older
93
- // builds put the message at `error.message`; current builds nest it
94
- // under `error.data.message`. Map known error class names to friendly
95
- // copy so the user gets actionable text instead of a class identifier.
96
- const rawErr = raw.error ?? raw.message;
97
- const errObj = rawErr && typeof rawErr === 'object' ? rawErr as Record<string, unknown> : null;
98
- const data = errObj && typeof errObj.data === 'object' && errObj.data
99
- ? errObj.data as Record<string, unknown>
100
- : null;
101
- const dataMessage = data && typeof data.message === 'string' ? data.message : null;
102
- const errMessage = errObj && typeof errObj.message === 'string' ? errObj.message : null;
103
- const errName = errObj && typeof errObj.name === 'string' ? errObj.name : null;
104
- const statusCode = data && typeof data.statusCode === 'number' ? data.statusCode : null;
105
-
106
- let content: string;
107
- if (typeof rawErr === 'string') {
108
- content = rawErr;
109
- } else if (dataMessage) {
110
- content = dataMessage;
111
- } else if (errMessage) {
112
- content = errMessage;
113
- } else if (errName) {
114
- const friendly: Record<string, string> = {
115
- ProviderModelNotFoundError: 'Model not found. Open Settings → Agents → OpenCode and pick a model from the live catalog (or run `opencode models --refresh`).',
116
- ProviderInitError: 'OpenCode provider config is invalid. Try `opencode auth login` or remove `~/.local/share/opencode/auth.json` and re-authenticate.',
117
- MessageOutputLengthError: 'OpenCode response was truncated by the model output cap. Try shortening the prompt or pick a model with a larger output limit.',
118
- AI_APICallError: 'OpenCode upstream API call failed. Clearing `~/.cache/opencode` and retrying usually fixes this.',
119
- APIError: statusCode === 429
120
- ? 'OpenCode hit a rate limit (429). Wait a few seconds and try again, or switch to a different model.'
121
- : 'OpenCode upstream API error.',
122
- };
123
- content = friendly[errName] ?? errName;
124
- } else {
125
- try { content = JSON.stringify(rawErr); }
126
- catch { content = 'Unknown OpenCode streaming error'; }
127
- }
128
- return [createNormalizedMessage({
129
- id: baseId,
130
- sessionId,
131
- timestamp: ts,
132
- provider: PROVIDER,
133
- kind: 'error',
134
- content,
135
- })];
136
- }
137
-
138
- return [];
139
- }
140
-
141
- async fetchHistory(
142
- sessionId: string,
143
- options: FetchHistoryOptions = {},
144
- ): Promise<FetchHistoryResult> {
145
- const { limit = null, offset = 0 } = options;
146
-
147
- let rawMessages: AnyRecord[] = [];
148
- try {
149
- rawMessages = sessionManager.getSessionMessages(sessionId) as AnyRecord[];
150
- } catch (error) {
151
- const message = error instanceof Error ? error.message : String(error);
152
- console.warn(`[OpencodeProvider] Failed to load session ${sessionId}:`, message);
153
- return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
154
- }
155
-
156
- const normalized: NormalizedMessage[] = [];
157
- for (const raw of rawMessages) {
158
- const ts = raw.timestamp || new Date().toISOString();
159
- const baseId = raw.uuid || raw.id || generateMessageId('opencode');
160
- const role = raw.message?.role || raw.role;
161
- const content = raw.message?.content || raw.content;
162
-
163
- if (!role || !content) continue;
164
- const normalizedRole = role === 'user' ? 'user' : 'assistant';
165
-
166
- if (typeof content === 'string' && content.trim()) {
167
- normalized.push(createNormalizedMessage({
168
- id: baseId,
169
- sessionId,
170
- timestamp: ts,
171
- provider: PROVIDER,
172
- kind: 'text',
173
- role: normalizedRole,
174
- content,
175
- }));
176
- }
177
- }
178
-
179
- const start = Math.max(0, offset);
180
- const pageLimit = limit === null ? null : Math.max(0, limit);
181
- const messages = pageLimit === null
182
- ? normalized.slice(start)
183
- : normalized.slice(start, start + pageLimit);
184
-
185
- return {
186
- messages,
187
- total: normalized.length,
188
- hasMore: pageLimit === null ? false : start + pageLimit < normalized.length,
189
- offset: start,
190
- limit: pageLimit,
191
- };
192
- }
193
- }
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
+ // OpenCode `--format json` emits errors as
91
+ // { type:"error", error:{ name, data:{ message, statusCode?, isRetryable? } } }
92
+ // — `error` is always an object wrapper, never a plain string. Older
93
+ // builds put the message at `error.message`; current builds nest it
94
+ // under `error.data.message`. Map known error class names to friendly
95
+ // copy so the user gets actionable text instead of a class identifier.
96
+ const rawErr = raw.error ?? raw.message;
97
+ const errObj = rawErr && typeof rawErr === 'object' ? rawErr as Record<string, unknown> : null;
98
+ const data = errObj && typeof errObj.data === 'object' && errObj.data
99
+ ? errObj.data as Record<string, unknown>
100
+ : null;
101
+ const dataMessage = data && typeof data.message === 'string' ? data.message : null;
102
+ const errMessage = errObj && typeof errObj.message === 'string' ? errObj.message : null;
103
+ const errName = errObj && typeof errObj.name === 'string' ? errObj.name : null;
104
+ const statusCode = data && typeof data.statusCode === 'number' ? data.statusCode : null;
105
+
106
+ let content: string;
107
+ if (typeof rawErr === 'string') {
108
+ content = rawErr;
109
+ } else if (dataMessage) {
110
+ content = dataMessage;
111
+ } else if (errMessage) {
112
+ content = errMessage;
113
+ } else if (errName) {
114
+ const friendly: Record<string, string> = {
115
+ ProviderModelNotFoundError: 'Model not found. Open Settings → Agents → OpenCode and pick a model from the live catalog (or run `opencode models --refresh`).',
116
+ ProviderInitError: 'OpenCode provider config is invalid. Try `opencode auth login` or remove `~/.local/share/opencode/auth.json` and re-authenticate.',
117
+ MessageOutputLengthError: 'OpenCode response was truncated by the model output cap. Try shortening the prompt or pick a model with a larger output limit.',
118
+ AI_APICallError: 'OpenCode upstream API call failed. Clearing `~/.cache/opencode` and retrying usually fixes this.',
119
+ APIError: statusCode === 429
120
+ ? 'OpenCode hit a rate limit (429). Wait a few seconds and try again, or switch to a different model.'
121
+ : 'OpenCode upstream API error.',
122
+ };
123
+ content = friendly[errName] ?? errName;
124
+ } else {
125
+ try { content = JSON.stringify(rawErr); }
126
+ catch { content = 'Unknown OpenCode streaming error'; }
127
+ }
128
+ return [createNormalizedMessage({
129
+ id: baseId,
130
+ sessionId,
131
+ timestamp: ts,
132
+ provider: PROVIDER,
133
+ kind: 'error',
134
+ content,
135
+ })];
136
+ }
137
+
138
+ return [];
139
+ }
140
+
141
+ async fetchHistory(
142
+ sessionId: string,
143
+ options: FetchHistoryOptions = {},
144
+ ): Promise<FetchHistoryResult> {
145
+ const { limit = null, offset = 0 } = options;
146
+
147
+ let rawMessages: AnyRecord[] = [];
148
+ try {
149
+ rawMessages = sessionManager.getSessionMessages(sessionId) as AnyRecord[];
150
+ } catch (error) {
151
+ const message = error instanceof Error ? error.message : String(error);
152
+ console.warn(`[OpencodeProvider] Failed to load session ${sessionId}:`, message);
153
+ return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
154
+ }
155
+
156
+ const normalized: NormalizedMessage[] = [];
157
+ for (const raw of rawMessages) {
158
+ const ts = raw.timestamp || new Date().toISOString();
159
+ const baseId = raw.uuid || raw.id || generateMessageId('opencode');
160
+ const role = raw.message?.role || raw.role;
161
+ const content = raw.message?.content || raw.content;
162
+
163
+ if (!role || !content) continue;
164
+ const normalizedRole = role === 'user' ? 'user' : 'assistant';
165
+
166
+ if (typeof content === 'string' && content.trim()) {
167
+ normalized.push(createNormalizedMessage({
168
+ id: baseId,
169
+ sessionId,
170
+ timestamp: ts,
171
+ provider: PROVIDER,
172
+ kind: 'text',
173
+ role: normalizedRole,
174
+ content,
175
+ }));
176
+ }
177
+ }
178
+
179
+ const start = Math.max(0, offset);
180
+ const pageLimit = limit === null ? null : Math.max(0, limit);
181
+ const messages = pageLimit === null
182
+ ? normalized.slice(start)
183
+ : normalized.slice(start, start + pageLimit);
184
+
185
+ return {
186
+ messages,
187
+ total: normalized.length,
188
+ hasMore: pageLimit === null ? false : start + pageLimit < normalized.length,
189
+ offset: start,
190
+ limit: pageLimit,
191
+ };
192
+ }
193
+ }