@pixelbyte-software/pixcode 1.33.9 → 1.33.10

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 (67) hide show
  1. package/dist/api-docs.html +395 -879
  2. package/dist/assets/{index-DpIcI9Q1.js → index-B_dU5AHA.js} +153 -165
  3. package/dist/favicon.svg +8 -8
  4. package/dist/icons/icon-128x128.svg +9 -9
  5. package/dist/icons/icon-144x144.svg +9 -9
  6. package/dist/icons/icon-152x152.svg +9 -9
  7. package/dist/icons/icon-192x192.svg +9 -9
  8. package/dist/icons/icon-384x384.svg +9 -9
  9. package/dist/icons/icon-512x512.svg +9 -9
  10. package/dist/icons/icon-72x72.svg +9 -9
  11. package/dist/icons/icon-96x96.svg +9 -9
  12. package/dist/icons/icon-template.svg +9 -9
  13. package/dist/index.html +1 -1
  14. package/dist/logo.svg +12 -12
  15. package/dist/openapi.yaml +1311 -0
  16. package/dist-server/server/gemini-cli.js +59 -0
  17. package/dist-server/server/gemini-cli.js.map +1 -1
  18. package/dist-server/server/index.js +6 -1
  19. package/dist-server/server/index.js.map +1 -1
  20. package/dist-server/server/middleware/auth.js +51 -9
  21. package/dist-server/server/middleware/auth.js.map +1 -1
  22. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +54 -15
  23. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js.map +1 -1
  24. package/dist-server/server/modules/providers/list/qwen/qwen-sessions.provider.js +46 -0
  25. package/dist-server/server/modules/providers/list/qwen/qwen-sessions.provider.js.map +1 -1
  26. package/dist-server/server/modules/providers/provider.routes.js +32 -1
  27. package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
  28. package/dist-server/server/opencode-cli.js +37 -1
  29. package/dist-server/server/opencode-cli.js.map +1 -1
  30. package/dist-server/server/opencode-response-handler.js +36 -34
  31. package/dist-server/server/opencode-response-handler.js.map +1 -1
  32. package/dist-server/server/routes/agent.js +187 -56
  33. package/dist-server/server/routes/agent.js.map +1 -1
  34. package/dist-server/server/routes/projects.js +134 -8
  35. package/dist-server/server/routes/projects.js.map +1 -1
  36. package/dist-server/server/services/provider-credentials.js +42 -8
  37. package/dist-server/server/services/provider-credentials.js.map +1 -1
  38. package/package.json +178 -178
  39. package/scripts/rest-sweep.mjs +93 -0
  40. package/server/database/db.js +794 -794
  41. package/server/database/json-store.js +194 -194
  42. package/server/gemini-cli.js +60 -0
  43. package/server/index.js +6 -1
  44. package/server/middleware/auth.js +50 -9
  45. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  46. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  47. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -193
  48. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  49. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  50. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  51. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -218
  52. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  53. package/server/modules/providers/provider.routes.ts +37 -4
  54. package/server/modules/providers/shared/provider-configs.ts +142 -142
  55. package/server/opencode-cli.js +37 -1
  56. package/server/opencode-response-handler.js +107 -100
  57. package/server/qwen-code-cli.js +395 -395
  58. package/server/qwen-response-handler.js +73 -73
  59. package/server/routes/agent.js +178 -58
  60. package/server/routes/projects.js +136 -8
  61. package/server/routes/qwen.js +27 -27
  62. package/server/services/external-access.js +171 -171
  63. package/server/services/provider-credentials.js +189 -155
  64. package/server/services/provider-models.js +381 -381
  65. package/server/services/telegram/telegram-http-client.js +130 -130
  66. package/server/services/vapid-keys.js +36 -36
  67. package/server/utils/port-access.js +209 -209
@@ -1,142 +1,142 @@
1
- /**
2
- * Registry of user-editable config files per provider CLI.
3
- *
4
- * This is the single source of truth for the Settings → Agents →
5
- * Configuration tab. Adding a new provider? Append a row here and the
6
- * UI + API pick it up — no component changes required.
7
- *
8
- * Rules:
9
- * - `relativePath` is relative to the user's home directory.
10
- * We never accept absolute paths from the client; the server
11
- * resolves these explicitly so path traversal is impossible.
12
- * - `format` drives the CodeMirror language extension on the client.
13
- * - `readonly: true` hides the Save button and the server rejects
14
- * writes. Use it for files the CLI owns (e.g. OAuth tokens).
15
- * - `description` is shown as a subtle caption under the editor.
16
- */
17
-
18
- export type ProviderConfigFormat = 'json' | 'toml' | 'env' | 'text';
19
-
20
- export type ProviderConfigFile = {
21
- id: string;
22
- label: string;
23
- relativePath: string;
24
- format: ProviderConfigFormat;
25
- readonly?: boolean;
26
- description?: string;
27
- };
28
-
29
- export const PROVIDER_CONFIG_FILES: Record<string, ProviderConfigFile[]> = {
30
- claude: [
31
- {
32
- id: 'settings',
33
- label: 'settings.json',
34
- relativePath: '.claude/settings.json',
35
- format: 'json',
36
- description: 'Main Claude Code settings — default model, system prompt, tool policy.',
37
- },
38
- {
39
- id: 'env',
40
- label: '.env',
41
- relativePath: '.claude/.env',
42
- format: 'env',
43
- description: 'Environment variables loaded when Claude runs (e.g. ANTHROPIC_API_KEY).',
44
- },
45
- ],
46
- codex: [
47
- {
48
- id: 'config',
49
- label: 'config.toml',
50
- relativePath: '.codex/config.toml',
51
- format: 'toml',
52
- description: 'Main Codex CLI config — models, MCP servers, approval policy, sandbox mode.',
53
- },
54
- {
55
- id: 'env',
56
- label: '.env',
57
- relativePath: '.codex/.env',
58
- format: 'env',
59
- description: 'Environment variables (OPENAI_API_KEY, OPENAI_BASE_URL, …).',
60
- },
61
- {
62
- id: 'auth',
63
- label: 'auth.json',
64
- relativePath: '.codex/auth.json',
65
- format: 'json',
66
- readonly: true,
67
- description: 'OAuth tokens managed by `codex login`. Read-only; editing here would corrupt the session.',
68
- },
69
- ],
70
- cursor: [
71
- {
72
- id: 'env',
73
- label: '.env',
74
- relativePath: '.cursor/.env',
75
- format: 'env',
76
- description: 'Cursor CLI environment variables.',
77
- },
78
- ],
79
- gemini: [
80
- {
81
- id: 'settings',
82
- label: 'settings.json',
83
- relativePath: '.gemini/settings.json',
84
- format: 'json',
85
- description: 'Main Gemini CLI settings — selected model, MCP servers, tool approval mode.',
86
- },
87
- {
88
- id: 'env',
89
- label: '.env',
90
- relativePath: '.gemini/.env',
91
- format: 'env',
92
- description: 'Environment variables (GOOGLE_API_KEY, GEMINI_API_KEY, …).',
93
- },
94
- ],
95
- qwen: [
96
- {
97
- id: 'settings',
98
- label: 'settings.json',
99
- relativePath: '.qwen/settings.json',
100
- format: 'json',
101
- description: 'Main Qwen Code settings — selected model, MCP servers, approval mode.',
102
- },
103
- {
104
- id: 'env',
105
- label: '.env',
106
- relativePath: '.qwen/.env',
107
- format: 'env',
108
- description: 'Environment variables (DASHSCOPE_API_KEY, OPENAI_API_KEY for OpenAI-compatible routes, …).',
109
- },
110
- ],
111
- opencode: [
112
- {
113
- id: 'config',
114
- label: 'opencode.json',
115
- relativePath: '.config/opencode/opencode.json',
116
- format: 'json',
117
- description: 'Main OpenCode config — provider, model, MCP servers, permission rules, agents.',
118
- },
119
- {
120
- id: 'tui',
121
- label: 'tui.json',
122
- relativePath: '.config/opencode/tui.json',
123
- format: 'json',
124
- description: 'Terminal UI preferences (theme, keybinds). Separate from the main config since 2026-02.',
125
- },
126
- {
127
- id: 'auth',
128
- label: 'auth.json',
129
- relativePath: '.local/share/opencode/auth.json',
130
- format: 'json',
131
- readonly: true,
132
- description: 'Provider credentials managed by `opencode auth login`. Read-only here; editing would corrupt stored OAuth tokens.',
133
- },
134
- ],
135
- };
136
-
137
- export const SUPPORTED_CONFIG_PROVIDERS = Object.keys(PROVIDER_CONFIG_FILES);
138
-
139
- // Hard cap — no config file we care about is remotely this big, but we
140
- // want to refuse reads and writes that would swell memory. Editing a 1 MB
141
- // settings.json is already a smell.
142
- export const MAX_CONFIG_FILE_SIZE_BYTES = 1_048_576; // 1 MB
1
+ /**
2
+ * Registry of user-editable config files per provider CLI.
3
+ *
4
+ * This is the single source of truth for the Settings → Agents →
5
+ * Configuration tab. Adding a new provider? Append a row here and the
6
+ * UI + API pick it up — no component changes required.
7
+ *
8
+ * Rules:
9
+ * - `relativePath` is relative to the user's home directory.
10
+ * We never accept absolute paths from the client; the server
11
+ * resolves these explicitly so path traversal is impossible.
12
+ * - `format` drives the CodeMirror language extension on the client.
13
+ * - `readonly: true` hides the Save button and the server rejects
14
+ * writes. Use it for files the CLI owns (e.g. OAuth tokens).
15
+ * - `description` is shown as a subtle caption under the editor.
16
+ */
17
+
18
+ export type ProviderConfigFormat = 'json' | 'toml' | 'env' | 'text';
19
+
20
+ export type ProviderConfigFile = {
21
+ id: string;
22
+ label: string;
23
+ relativePath: string;
24
+ format: ProviderConfigFormat;
25
+ readonly?: boolean;
26
+ description?: string;
27
+ };
28
+
29
+ export const PROVIDER_CONFIG_FILES: Record<string, ProviderConfigFile[]> = {
30
+ claude: [
31
+ {
32
+ id: 'settings',
33
+ label: 'settings.json',
34
+ relativePath: '.claude/settings.json',
35
+ format: 'json',
36
+ description: 'Main Claude Code settings — default model, system prompt, tool policy.',
37
+ },
38
+ {
39
+ id: 'env',
40
+ label: '.env',
41
+ relativePath: '.claude/.env',
42
+ format: 'env',
43
+ description: 'Environment variables loaded when Claude runs (e.g. ANTHROPIC_API_KEY).',
44
+ },
45
+ ],
46
+ codex: [
47
+ {
48
+ id: 'config',
49
+ label: 'config.toml',
50
+ relativePath: '.codex/config.toml',
51
+ format: 'toml',
52
+ description: 'Main Codex CLI config — models, MCP servers, approval policy, sandbox mode.',
53
+ },
54
+ {
55
+ id: 'env',
56
+ label: '.env',
57
+ relativePath: '.codex/.env',
58
+ format: 'env',
59
+ description: 'Environment variables (OPENAI_API_KEY, OPENAI_BASE_URL, …).',
60
+ },
61
+ {
62
+ id: 'auth',
63
+ label: 'auth.json',
64
+ relativePath: '.codex/auth.json',
65
+ format: 'json',
66
+ readonly: true,
67
+ description: 'OAuth tokens managed by `codex login`. Read-only; editing here would corrupt the session.',
68
+ },
69
+ ],
70
+ cursor: [
71
+ {
72
+ id: 'env',
73
+ label: '.env',
74
+ relativePath: '.cursor/.env',
75
+ format: 'env',
76
+ description: 'Cursor CLI environment variables.',
77
+ },
78
+ ],
79
+ gemini: [
80
+ {
81
+ id: 'settings',
82
+ label: 'settings.json',
83
+ relativePath: '.gemini/settings.json',
84
+ format: 'json',
85
+ description: 'Main Gemini CLI settings — selected model, MCP servers, tool approval mode.',
86
+ },
87
+ {
88
+ id: 'env',
89
+ label: '.env',
90
+ relativePath: '.gemini/.env',
91
+ format: 'env',
92
+ description: 'Environment variables (GOOGLE_API_KEY, GEMINI_API_KEY, …).',
93
+ },
94
+ ],
95
+ qwen: [
96
+ {
97
+ id: 'settings',
98
+ label: 'settings.json',
99
+ relativePath: '.qwen/settings.json',
100
+ format: 'json',
101
+ description: 'Main Qwen Code settings — selected model, MCP servers, approval mode.',
102
+ },
103
+ {
104
+ id: 'env',
105
+ label: '.env',
106
+ relativePath: '.qwen/.env',
107
+ format: 'env',
108
+ description: 'Environment variables (DASHSCOPE_API_KEY, OPENAI_API_KEY for OpenAI-compatible routes, …).',
109
+ },
110
+ ],
111
+ opencode: [
112
+ {
113
+ id: 'config',
114
+ label: 'opencode.json',
115
+ relativePath: '.config/opencode/opencode.json',
116
+ format: 'json',
117
+ description: 'Main OpenCode config — provider, model, MCP servers, permission rules, agents.',
118
+ },
119
+ {
120
+ id: 'tui',
121
+ label: 'tui.json',
122
+ relativePath: '.config/opencode/tui.json',
123
+ format: 'json',
124
+ description: 'Terminal UI preferences (theme, keybinds). Separate from the main config since 2026-02.',
125
+ },
126
+ {
127
+ id: 'auth',
128
+ label: 'auth.json',
129
+ relativePath: '.local/share/opencode/auth.json',
130
+ format: 'json',
131
+ readonly: true,
132
+ description: 'Provider credentials managed by `opencode auth login`. Read-only here; editing would corrupt stored OAuth tokens.',
133
+ },
134
+ ],
135
+ };
136
+
137
+ export const SUPPORTED_CONFIG_PROVIDERS = Object.keys(PROVIDER_CONFIG_FILES);
138
+
139
+ // Hard cap — no config file we care about is remotely this big, but we
140
+ // want to refuse reads and writes that would swell memory. Editing a 1 MB
141
+ // settings.json is already a smell.
142
+ export const MAX_CONFIG_FILE_SIZE_BYTES = 1_048_576; // 1 MB
@@ -50,13 +50,34 @@ function mapPermissionModeToArgs(permissionMode, skipPermissions) {
50
50
  return { agent: 'build', dangerously: false };
51
51
  }
52
52
 
53
+ // Pixcode stores OpenCode permissions as two flat lists (`allowPatterns`,
54
+ // `denyPatterns`) in `opencode-settings` localStorage; the backend collapses
55
+ // them into the JSON shape OpenCode reads from `opencode.json`. We pass the
56
+ // merged config inline via `OPENCODE_CONFIG_CONTENT` (a documented OpenCode
57
+ // env var) instead of writing to disk — that way Pixcode's intent doesn't
58
+ // pollute the user's project tree, and project-local opencode.json overrides
59
+ // still take precedence per OpenCode's own precedence rules.
60
+ function buildOpencodePermissionConfig(settings) {
61
+ const allow = Array.isArray(settings?.allowPatterns) ? settings.allowPatterns.filter(Boolean) : [];
62
+ const deny = Array.isArray(settings?.denyPatterns) ? settings.denyPatterns.filter(Boolean) : [];
63
+ if (!allow.length && !deny.length) return null;
64
+
65
+ const bash = {};
66
+ // Deny rules win when patterns collide — apply allow first so deny
67
+ // overwrites duplicates.
68
+ for (const pattern of allow) bash[pattern] = 'allow';
69
+ for (const pattern of deny) bash[pattern] = 'deny';
70
+
71
+ return { permission: { bash } };
72
+ }
73
+
53
74
  async function spawnOpencode(command, options = {}, ws) {
54
75
  const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary, agent: agentOverride } = options;
55
76
  let capturedSessionId = sessionId;
56
77
  let sessionCreatedSent = false;
57
78
  let assistantBlocks = [];
58
79
 
59
- const settings = toolsSettings || { allowedTools: [], disallowedTools: [], skipPermissions: false };
80
+ const settings = toolsSettings || { allowPatterns: [], denyPatterns: [], skipPermissions: false };
60
81
 
61
82
  const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
62
83
  const args = ['run', '--format', 'json'];
@@ -135,6 +156,21 @@ async function spawnOpencode(command, options = {}, ws) {
135
156
 
136
157
  const spawnEnv = await buildSpawnEnv('opencode');
137
158
 
159
+ // Inject Pixcode's permission allow/deny patterns as inline OpenCode config.
160
+ // Skipped when `--dangerously-skip-permissions` is on (the flag overrides
161
+ // the config anyway) and when both lists are empty (avoid clobbering a
162
+ // project-local opencode.json the user has hand-tuned).
163
+ if (!dangerously) {
164
+ const permConfig = buildOpencodePermissionConfig(settings);
165
+ if (permConfig) {
166
+ try {
167
+ spawnEnv.OPENCODE_CONFIG_CONTENT = JSON.stringify(permConfig);
168
+ } catch (error) {
169
+ console.warn('[opencode] Failed to serialize permission config:', error?.message || error);
170
+ }
171
+ }
172
+ }
173
+
138
174
  return new Promise((resolve, reject) => {
139
175
  const opencodeProcess = spawnFunction(spawnCmd, spawnArgs, {
140
176
  cwd: workingDir,
@@ -1,100 +1,107 @@
1
- // OpenCode Response Handler — `opencode run --format json` parser.
2
- //
3
- // The JSON format streams one event per line (NDJSON). Event shapes follow
4
- // the OpenAPI contract exposed by `opencode serve`. We treat the stream
5
- // permissively: lines that don't parse as JSON are passed through as plain
6
- // text deltas (covers OpenCode's pre-stream banner output and any debug
7
- // noise the CLI emits to stdout).
8
- import { sessionsService } from './modules/providers/services/sessions.service.js';
9
-
10
- class OpencodeResponseHandler {
11
- constructor(ws, options = {}) {
12
- this.ws = ws;
13
- this.buffer = '';
14
- this.onContentFragment = options.onContentFragment || null;
15
- this.onInit = options.onInit || null;
16
- this.onToolUse = options.onToolUse || null;
17
- this.onToolResult = options.onToolResult || null;
18
- }
19
-
20
- processData(data) {
21
- this.buffer += data;
22
-
23
- const lines = this.buffer.split('\n');
24
- this.buffer = lines.pop() || '';
25
-
26
- for (const line of lines) {
27
- const trimmed = line.trim();
28
- if (!trimmed) continue;
29
- try {
30
- const event = JSON.parse(trimmed);
31
- this.handleEvent(event);
32
- } catch {
33
- // Non-JSON line — surface as plain text delta so the user sees CLI
34
- // banners / status messages instead of swallowing them silently.
35
- if (this.onContentFragment) this.onContentFragment(trimmed + '\n');
36
- }
37
- }
38
- }
39
-
40
- handleEvent(event) {
41
- const sid = typeof this.ws.getSessionId === 'function' ? this.ws.getSessionId() : null;
42
-
43
- if (event.type === 'init' || event.type === 'session.start') {
44
- if (this.onInit) this.onInit(event);
45
- return;
46
- }
47
-
48
- // OpenCode emits assistant text as either a top-level `text` event
49
- // (current `--format json` shape: `{ type: "text", part: { text } }`)
50
- // or as `message`/`part` legacy shapes from earlier builds. Cover all
51
- // three so we don't drop tokens on a CLI version we haven't matched.
52
- if (event.type === 'text' && event.part && typeof event.part.text === 'string') {
53
- if (this.onContentFragment && event.part.text) this.onContentFragment(event.part.text);
54
- } else if (event.type === 'message' && event.role === 'assistant') {
55
- const content = event.content || event.text || '';
56
- if (this.onContentFragment && content) this.onContentFragment(content);
57
- } else if (event.type === 'part' && event.part_type === 'text') {
58
- const content = event.text || event.content || '';
59
- if (this.onContentFragment && content) this.onContentFragment(content);
60
- } else if (event.type === 'tool_use' || event.type === 'tool-use' || event.type === 'tool.start') {
61
- // Tool-use shape on `--format json`: `{ type:"tool_use", part:{ callID, tool, state:{ input } } }`
62
- const part = event.part || event;
63
- if (this.onToolUse) this.onToolUse({
64
- tool_id: part.callID || part.id || event.tool_id,
65
- tool_name: part.tool || part.name || event.tool_name,
66
- parameters: part.state?.input || part.input || event.parameters || {},
67
- });
68
- } else if (event.type === 'tool_result' || event.type === 'tool-result' || event.type === 'tool.end') {
69
- const part = event.part || event;
70
- const state = part.state || {};
71
- if (this.onToolResult) this.onToolResult({
72
- tool_id: part.callID || part.id || event.tool_id,
73
- output: state.output ?? part.output ?? event.output ?? event.result ?? '',
74
- status: state.status || event.status || (event.isError ? 'error' : 'ok'),
75
- });
76
- }
77
-
78
- const normalized = sessionsService.normalizeMessage('opencode', event, sid);
79
- for (const msg of normalized) {
80
- this.ws.send(msg);
81
- }
82
- }
83
-
84
- forceFlush() {
85
- if (this.buffer.trim()) {
86
- try {
87
- const event = JSON.parse(this.buffer);
88
- this.handleEvent(event);
89
- } catch {
90
- if (this.onContentFragment) this.onContentFragment(this.buffer);
91
- }
92
- }
93
- }
94
-
95
- destroy() {
96
- this.buffer = '';
97
- }
98
- }
99
-
100
- export default OpencodeResponseHandler;
1
+ // OpenCode Response Handler — `opencode run --format json` parser.
2
+ //
3
+ // The JSON format streams one event per line (NDJSON). Verified shapes
4
+ // (opencode-ai 0.x, see opencode.ai/docs/cli):
5
+ //
6
+ // { type:"step_start", timestamp, sessionID, part:{ type:"step-start", id, messageID, sessionID } }
7
+ // { type:"text", timestamp, sessionID, part:{ type:"text", id, messageID, sessionID, text:"…", time:{…}, metadata:{…} } }
8
+ // { type:"tool_use", timestamp, sessionID, part:{ type:"tool-use", callID, tool, state:{ input } } }
9
+ // { type:"tool_result", timestamp, sessionID, part:{ type:"tool-result", callID, state:{ output, status } } }
10
+ // { type:"step_finish", timestamp, sessionID, part:{ type:"step-finish", reason, tokens, cost } }
11
+ // { type:"error", timestamp, sessionID, error:{ name, data:{ message, statusCode? } } }
12
+ //
13
+ // Important: field names are camelCase — `sessionID`, `callID`, `messageID`.
14
+ // Earlier integration code assumed snake_case (`session_id`, `tool_id`) which
15
+ // is wrong; nothing in `opencode run --format json` uses snake_case.
16
+ //
17
+ // Lines that don't parse as JSON are surfaced as plain text deltas (covers
18
+ // the CLI's pre-stream banner output, "Shell cwd was reset to …" notices on
19
+ // Windows, and any debug noise).
20
+ import { sessionsService } from './modules/providers/services/sessions.service.js';
21
+
22
+ class OpencodeResponseHandler {
23
+ constructor(ws, options = {}) {
24
+ this.ws = ws;
25
+ this.buffer = '';
26
+ this.onContentFragment = options.onContentFragment || null;
27
+ this.onInit = options.onInit || null;
28
+ this.onToolUse = options.onToolUse || null;
29
+ this.onToolResult = options.onToolResult || null;
30
+ this.capturedCliSessionId = null;
31
+ }
32
+
33
+ processData(data) {
34
+ this.buffer += data;
35
+
36
+ const lines = this.buffer.split('\n');
37
+ this.buffer = lines.pop() || '';
38
+
39
+ for (const line of lines) {
40
+ const trimmed = line.trim();
41
+ if (!trimmed) continue;
42
+ try {
43
+ const event = JSON.parse(trimmed);
44
+ this.handleEvent(event);
45
+ } catch {
46
+ // Non-JSON line — surface as plain text delta so the user sees CLI
47
+ // banners / status messages instead of swallowing them silently.
48
+ if (this.onContentFragment) this.onContentFragment(trimmed + '\n');
49
+ }
50
+ }
51
+ }
52
+
53
+ handleEvent(event) {
54
+ const sid = typeof this.ws.getSessionId === 'function' ? this.ws.getSessionId() : null;
55
+
56
+ // Capture OpenCode's real session ID (e.g. `ses_22d6…`) the first time we
57
+ // see one. Every event carries `sessionID` at the top level — we don't
58
+ // wait for an `init`/`session.start` event because OpenCode `run --format
59
+ // json` never emits those (the first event is always `step_start`).
60
+ if (!this.capturedCliSessionId && typeof event.sessionID === 'string' && event.sessionID) {
61
+ this.capturedCliSessionId = event.sessionID;
62
+ if (this.onInit) this.onInit({ session_id: event.sessionID, sessionID: event.sessionID });
63
+ }
64
+
65
+ const part = event.part && typeof event.part === 'object' ? event.part : null;
66
+
67
+ if (event.type === 'text' && part && typeof part.text === 'string') {
68
+ if (this.onContentFragment && part.text) this.onContentFragment(part.text);
69
+ } else if (event.type === 'tool_use' || event.type === 'tool-use' || event.type === 'tool.start') {
70
+ const state = part?.state && typeof part.state === 'object' ? part.state : {};
71
+ if (this.onToolUse) this.onToolUse({
72
+ tool_id: part?.callID || part?.id || event.tool_id || '',
73
+ tool_name: part?.tool || part?.name || event.tool_name || '',
74
+ parameters: state.input || part?.input || event.parameters || {},
75
+ });
76
+ } else if (event.type === 'tool_result' || event.type === 'tool-result' || event.type === 'tool.end') {
77
+ const state = part?.state && typeof part.state === 'object' ? part.state : {};
78
+ if (this.onToolResult) this.onToolResult({
79
+ tool_id: part?.callID || part?.id || event.tool_id || '',
80
+ output: state.output ?? part?.output ?? event.output ?? event.result ?? '',
81
+ status: state.status || event.status || (event.isError ? 'error' : 'ok'),
82
+ });
83
+ }
84
+
85
+ const normalized = sessionsService.normalizeMessage('opencode', event, sid);
86
+ for (const msg of normalized) {
87
+ this.ws.send(msg);
88
+ }
89
+ }
90
+
91
+ forceFlush() {
92
+ if (this.buffer.trim()) {
93
+ try {
94
+ const event = JSON.parse(this.buffer);
95
+ this.handleEvent(event);
96
+ } catch {
97
+ if (this.onContentFragment) this.onContentFragment(this.buffer);
98
+ }
99
+ }
100
+ }
101
+
102
+ destroy() {
103
+ this.buffer = '';
104
+ }
105
+ }
106
+
107
+ export default OpencodeResponseHandler;