@myrialabs/clopen 0.3.8 → 0.3.9

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 (125) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  4. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  5. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  6. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  7. package/backend/database/migrations/index.ts +29 -1
  8. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  9. package/backend/database/queries/engine-queries.ts +12 -0
  10. package/backend/database/queries/project-queries.ts +10 -5
  11. package/backend/engine/README.md +1702 -0
  12. package/backend/engine/adapters/claude/models.ts +141 -0
  13. package/backend/engine/adapters/claude/stream.ts +1 -1
  14. package/backend/engine/adapters/codex/credential.ts +179 -0
  15. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  16. package/backend/engine/adapters/codex/index.ts +1 -0
  17. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  18. package/backend/engine/adapters/codex/models.ts +105 -0
  19. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  20. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  21. package/backend/engine/adapters/codex/stream.ts +310 -0
  22. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  23. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  24. package/backend/engine/adapters/copilot/index.ts +1 -0
  25. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  26. package/backend/engine/adapters/copilot/models.ts +92 -0
  27. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  28. package/backend/engine/adapters/copilot/stream.ts +573 -0
  29. package/backend/engine/adapters/opencode/config.ts +56 -104
  30. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  31. package/backend/engine/adapters/opencode/models.ts +79 -0
  32. package/backend/engine/adapters/opencode/presets.ts +91 -0
  33. package/backend/engine/adapters/opencode/stream.ts +5 -115
  34. package/backend/engine/adapters/qwen/credential.ts +78 -0
  35. package/backend/engine/adapters/qwen/environment.ts +84 -0
  36. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  37. package/backend/engine/adapters/qwen/index.ts +1 -0
  38. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  39. package/backend/engine/adapters/qwen/models.ts +81 -0
  40. package/backend/engine/adapters/qwen/presets.ts +51 -0
  41. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  42. package/backend/engine/adapters/qwen/stream.ts +380 -0
  43. package/backend/engine/index.ts +35 -0
  44. package/backend/engine/install-recipes.ts +80 -1
  45. package/backend/engine/install-runner.ts +4 -0
  46. package/backend/mcp/README.md +84 -14
  47. package/backend/mcp/config.ts +218 -17
  48. package/backend/mcp/index.ts +2 -0
  49. package/backend/mcp/project-context.ts +55 -0
  50. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  51. package/backend/mcp/servers/helper.ts +13 -0
  52. package/backend/middleware/error-handler.ts +16 -2
  53. package/backend/preview/browser/browser-preview-service.ts +4 -4
  54. package/backend/ws/README.md +128 -3
  55. package/backend/ws/access.ts +56 -0
  56. package/backend/ws/chat/stream.ts +36 -12
  57. package/backend/ws/db-client/access.ts +19 -0
  58. package/backend/ws/db-client/connections.ts +31 -17
  59. package/backend/ws/db-client/io.ts +7 -9
  60. package/backend/ws/db-client/query.ts +83 -31
  61. package/backend/ws/db-client/schema.ts +9 -4
  62. package/backend/ws/db-client/structure.ts +22 -10
  63. package/backend/ws/engine/access.ts +39 -0
  64. package/backend/ws/engine/claude/accounts.ts +15 -10
  65. package/backend/ws/engine/codex/accounts.ts +516 -0
  66. package/backend/ws/engine/codex/index.ts +14 -0
  67. package/backend/ws/engine/codex/status.ts +87 -0
  68. package/backend/ws/engine/copilot/accounts.ts +122 -0
  69. package/backend/ws/engine/copilot/index.ts +13 -0
  70. package/backend/ws/engine/copilot/status.ts +54 -0
  71. package/backend/ws/engine/index.ts +7 -1
  72. package/backend/ws/engine/opencode/providers.ts +1 -1
  73. package/backend/ws/engine/qwen/accounts.ts +137 -0
  74. package/backend/ws/engine/qwen/index.ts +15 -0
  75. package/backend/ws/engine/qwen/presets.ts +40 -0
  76. package/backend/ws/engine/qwen/status.ts +54 -0
  77. package/backend/ws/files/read.ts +3 -1
  78. package/backend/ws/files/state.ts +3 -0
  79. package/backend/ws/files/watch.ts +7 -1
  80. package/backend/ws/git/branch.ts +13 -19
  81. package/backend/ws/git/commit-message.ts +3 -4
  82. package/backend/ws/git/commit.ts +5 -7
  83. package/backend/ws/git/conflict.ts +7 -10
  84. package/backend/ws/git/diff.ts +7 -10
  85. package/backend/ws/git/log.ts +3 -4
  86. package/backend/ws/git/remote.ts +30 -43
  87. package/backend/ws/git/staging.ts +13 -19
  88. package/backend/ws/git/status.ts +7 -11
  89. package/backend/ws/messages/crud.ts +7 -13
  90. package/backend/ws/preview/access.ts +45 -0
  91. package/backend/ws/preview/browser/cleanup.ts +3 -11
  92. package/backend/ws/preview/browser/console.ts +5 -40
  93. package/backend/ws/preview/browser/interact.ts +2 -6
  94. package/backend/ws/preview/browser/native-ui.ts +5 -18
  95. package/backend/ws/preview/browser/stats.ts +2 -12
  96. package/backend/ws/preview/browser/tab-info.ts +4 -20
  97. package/backend/ws/preview/browser/tab.ts +4 -27
  98. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  99. package/backend/ws/projects/crud.ts +4 -10
  100. package/backend/ws/projects/status.ts +2 -0
  101. package/backend/ws/sessions/crud.ts +22 -33
  102. package/backend/ws/settings/crud.ts +13 -13
  103. package/backend/ws/snapshot/restore.ts +5 -2
  104. package/backend/ws/snapshot/timeline.ts +3 -1
  105. package/backend/ws/system-tools/access.ts +28 -0
  106. package/backend/ws/system-tools/install.ts +13 -4
  107. package/backend/ws/system-tools/status.ts +5 -2
  108. package/backend/ws/terminal/access.ts +56 -0
  109. package/backend/ws/terminal/persistence.ts +12 -6
  110. package/backend/ws/terminal/session.ts +35 -14
  111. package/backend/ws/terminal/stream.ts +4 -1
  112. package/dist/assets/{index-DqAGCTFT.js → index-D8V2wj9B.js} +2 -2
  113. package/dist/assets/{main-DsED0rLr.js → main-C9nYVmnw.js} +206 -198
  114. package/dist/assets/main-hspyFOoK.css +1 -0
  115. package/dist/index.html +2 -2
  116. package/package.json +4 -1
  117. package/shared/constants/engines.ts +45 -140
  118. package/shared/types/database/schema.ts +1 -0
  119. package/shared/types/unified/common.ts +1 -1
  120. package/shared/types/unified/engine.ts +29 -1
  121. package/shared/types/unified/index.ts +2 -0
  122. package/shared/types/unified/message.ts +1 -1
  123. package/shared/types/unified/tool.ts +17 -2
  124. package/shared/utils/ws-server.ts +14 -0
  125. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Claude Code model catalog.
3
+ *
4
+ * Static catalog — the Anthropic Agent SDK accepts these IDs directly via
5
+ * the `model` option, no runtime discovery endpoint is needed. Update when
6
+ * Anthropic ships a new generation.
7
+ */
8
+
9
+ import type { EngineModel } from '$shared/types/unified';
10
+
11
+ export const CLAUDE_CODE_MODELS: EngineModel[] = [
12
+ {
13
+ engine: {
14
+ type: 'claude-code',
15
+ provider: 'anthropic',
16
+ model: {
17
+ id: 'claude-opus-4-7',
18
+ name: 'Claude Opus 4.7',
19
+ },
20
+ account: {
21
+ id: 0,
22
+ name: '',
23
+ },
24
+ },
25
+ limit: {
26
+ input: 200_000,
27
+ output: 128_000,
28
+ },
29
+ modalities: {
30
+ input: {
31
+ text: true,
32
+ image: true,
33
+ audio: false,
34
+ video: false,
35
+ pdf: true,
36
+ },
37
+ output: {
38
+ text: true,
39
+ image: false,
40
+ audio: false,
41
+ video: false,
42
+ pdf: false,
43
+ },
44
+ },
45
+ capabilities: {
46
+ reasoning: true,
47
+ tools: true,
48
+ structuredOutput: true,
49
+ },
50
+ cost: {
51
+ input: 5,
52
+ output: 25,
53
+ },
54
+ },
55
+ {
56
+ engine: {
57
+ type: 'claude-code',
58
+ provider: 'anthropic',
59
+ model: {
60
+ id: 'claude-sonnet-4-6',
61
+ name: 'Claude Sonnet 4.6',
62
+ },
63
+ account: {
64
+ id: 0,
65
+ name: '',
66
+ },
67
+ },
68
+ limit: {
69
+ input: 200_000,
70
+ output: 64_000,
71
+ },
72
+ modalities: {
73
+ input: {
74
+ text: true,
75
+ image: true,
76
+ audio: false,
77
+ video: false,
78
+ pdf: true,
79
+ },
80
+ output: {
81
+ text: true,
82
+ image: false,
83
+ audio: false,
84
+ video: false,
85
+ pdf: false,
86
+ },
87
+ },
88
+ capabilities: {
89
+ reasoning: true,
90
+ tools: true,
91
+ structuredOutput: true,
92
+ },
93
+ cost: {
94
+ input: 3,
95
+ output: 15,
96
+ },
97
+ },
98
+ {
99
+ engine: {
100
+ type: 'claude-code',
101
+ provider: 'anthropic',
102
+ model: {
103
+ id: 'claude-haiku-4-5',
104
+ name: 'Claude Haiku 4.5',
105
+ },
106
+ account: {
107
+ id: 0,
108
+ name: '',
109
+ },
110
+ },
111
+ limit: {
112
+ input: 200_000,
113
+ output: 64_000,
114
+ },
115
+ modalities: {
116
+ input: {
117
+ text: true,
118
+ image: true,
119
+ audio: false,
120
+ video: false,
121
+ pdf: true,
122
+ },
123
+ output: {
124
+ text: true,
125
+ image: false,
126
+ audio: false,
127
+ video: false,
128
+ pdf: false,
129
+ },
130
+ },
131
+ capabilities: {
132
+ reasoning: true,
133
+ tools: true,
134
+ structuredOutput: true,
135
+ },
136
+ cost: {
137
+ input: 1,
138
+ output: 5,
139
+ },
140
+ },
141
+ ];
@@ -29,7 +29,7 @@ import { handleStreamError } from './error-handler';
29
29
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
30
30
  import type { AIEngine, EngineQueryOptions } from '../../types';
31
31
  import type { EngineModel } from '$shared/types/unified';
32
- import { CLAUDE_CODE_MODELS } from '$shared/constants/engines';
32
+ import { CLAUDE_CODE_MODELS } from './models';
33
33
 
34
34
  import { debug } from '$shared/utils/logger';
35
35
 
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Codex credential resolution: dual-mode credential storage + shared `~/.codex/auth.json` swap.
3
+ *
4
+ * Codex supports two auth modes:
5
+ * - **API key** — paste `sk-…` token; `Codex({ apiKey })` auto-injects it
6
+ * into the spawned subprocess.
7
+ * - **ChatGPT** — browser OAuth via `codex login`; the CLI writes
8
+ * `~/.codex/auth.json` and refreshes it in-place.
9
+ *
10
+ * Multi-account ChatGPT support uses the **auth-blob swap** pattern (see
11
+ * backend/engine/README.md §9.13): we snapshot `~/.codex/auth.json` content
12
+ * into `engine_accounts.credential` after login, and write the active
13
+ * account's snapshot back to the shared file on switch / stream-start.
14
+ *
15
+ * Trade-off: only one Codex account is "active on disk" at a time. Concurrent
16
+ * streams from two ChatGPT accounts would race; our UI surfaces only one
17
+ * active account per engine, so that constraint already holds for MVP.
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import os from 'node:os';
23
+ import { engineQueries, type EngineAccount } from '../../../database/queries/engine-queries';
24
+ import { debug } from '$shared/utils/logger';
25
+
26
+ const CODEX_HOME = path.join(os.homedir(), '.codex');
27
+ const AUTH_JSON_PATH = path.join(CODEX_HOME, 'auth.json');
28
+ const AUTH_JSON_TMP_PATH = path.join(CODEX_HOME, 'auth.json.tmp');
29
+
30
+ // ============================================================================
31
+ // Credential JSON wrapper
32
+ // ============================================================================
33
+
34
+ export type CodexCredential =
35
+ | { kind: 'api_key'; apiKey: string }
36
+ | { kind: 'chatgpt'; authJson: string };
37
+
38
+ /**
39
+ * Parse the JSON wrapper stored in `engine_accounts.credential`.
40
+ *
41
+ * Both auth modes are stored as JSON so we can dispatch on `kind` at
42
+ * stream-start without spawning a CLI to detect.
43
+ */
44
+ export function parseCodexCredential(raw: string): CodexCredential | null {
45
+ try {
46
+ const parsed = JSON.parse(raw) as CodexCredential | { kind?: string };
47
+ if (parsed && (parsed as CodexCredential).kind === 'api_key' && typeof (parsed as { apiKey?: unknown }).apiKey === 'string') {
48
+ return parsed as CodexCredential;
49
+ }
50
+ if (parsed && (parsed as CodexCredential).kind === 'chatgpt' && typeof (parsed as { authJson?: unknown }).authJson === 'string') {
51
+ return parsed as CodexCredential;
52
+ }
53
+ return null;
54
+ } catch {
55
+ // Backwards-compat: if the row was created by an older path that wrote a
56
+ // raw API key without the JSON wrapper, treat it as an API key.
57
+ if (raw.startsWith('sk-') || raw.startsWith('sk_')) {
58
+ return { kind: 'api_key', apiKey: raw };
59
+ }
60
+ return null;
61
+ }
62
+ }
63
+
64
+ export function serializeCodexCredential(cred: CodexCredential): string {
65
+ return JSON.stringify(cred);
66
+ }
67
+
68
+ /** True when the model requires a ChatGPT-mode account (e.g. gpt-5.5). */
69
+ export function authModeOf(account: EngineAccount): 'api_key' | 'chatgpt' | null {
70
+ const parsed = parseCodexCredential(account.credential);
71
+ return parsed?.kind ?? null;
72
+ }
73
+
74
+ // ============================================================================
75
+ // Shared `~/.codex/auth.json` swap
76
+ // ============================================================================
77
+
78
+ function ensureCodexHome(): void {
79
+ if (!fs.existsSync(CODEX_HOME)) {
80
+ fs.mkdirSync(CODEX_HOME, { recursive: true });
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Atomically replace `~/.codex/auth.json` with the given content. Writes to a
86
+ * sibling tmp file then renames so a concurrent reader never sees a torn write.
87
+ */
88
+ export function writeAuthJson(content: string): void {
89
+ ensureCodexHome();
90
+ fs.writeFileSync(AUTH_JSON_TMP_PATH, content, { encoding: 'utf-8' });
91
+ fs.renameSync(AUTH_JSON_TMP_PATH, AUTH_JSON_PATH);
92
+ }
93
+
94
+ /** Read the current `~/.codex/auth.json` content, or null if absent. */
95
+ export function readAuthJson(): string | null {
96
+ try {
97
+ return fs.readFileSync(AUTH_JSON_PATH, 'utf-8');
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ export function authJsonExists(): boolean {
104
+ return fs.existsSync(AUTH_JSON_PATH);
105
+ }
106
+
107
+ export function getAuthJsonPath(): string {
108
+ return AUTH_JSON_PATH;
109
+ }
110
+
111
+ export function getCodexHomeDir(): string {
112
+ return CODEX_HOME;
113
+ }
114
+
115
+ // ============================================================================
116
+ // Apply / persist auth from / to DB
117
+ // ============================================================================
118
+
119
+ /**
120
+ * Apply the given account's credential to the runtime so the next Codex
121
+ * subprocess picks it up:
122
+ * - `chatgpt` → write `authJson` blob into the shared `~/.codex/auth.json`
123
+ * (only if it differs from the current file content).
124
+ * - `api_key` → no filesystem mutation; caller supplies `apiKey` to
125
+ * `new Codex({ apiKey })`.
126
+ *
127
+ * Returns the parsed credential for downstream consumption (apiKey lookup).
128
+ */
129
+ export function applyAccountAuth(account: EngineAccount): CodexCredential | null {
130
+ const cred = parseCodexCredential(account.credential);
131
+ if (!cred) {
132
+ debug.warn('engine', `Codex: account ${account.id} has unrecognised credential format`);
133
+ return null;
134
+ }
135
+
136
+ if (cred.kind === 'chatgpt') {
137
+ // Idempotent: skip write if the file already matches (the CLI's own
138
+ // token-refresh path mutates this same file in place — we don't want
139
+ // to clobber a fresher token with a stale snapshot).
140
+ const current = readAuthJson();
141
+ if (current !== cred.authJson) {
142
+ writeAuthJson(cred.authJson);
143
+ debug.log('engine', `Codex: wrote auth.json from account "${account.name}" (${cred.authJson.length} bytes)`);
144
+ }
145
+ }
146
+
147
+ return cred;
148
+ }
149
+
150
+ /**
151
+ * Snapshot the current `~/.codex/auth.json` back into the active ChatGPT
152
+ * account's credential row. Called after a stream finishes so any token
153
+ * refresh the CLI performed during the turn survives across account switches.
154
+ *
155
+ * No-op when:
156
+ * - There's no active Codex account.
157
+ * - The active account is API-key mode (auth.json wasn't touched).
158
+ * - The auth.json file doesn't exist.
159
+ * - The on-disk content is identical to what we already have stored.
160
+ */
161
+ export function snapshotAuthJsonToActiveAccount(): void {
162
+ const account = engineQueries.getActiveAccountForEngine('codex');
163
+ if (!account) return;
164
+
165
+ const parsed = parseCodexCredential(account.credential);
166
+ if (!parsed || parsed.kind !== 'chatgpt') return;
167
+
168
+ const current = readAuthJson();
169
+ if (current === null) return;
170
+ if (current === parsed.authJson) return;
171
+
172
+ const updated = serializeCodexCredential({ kind: 'chatgpt', authJson: current });
173
+ try {
174
+ engineQueries.updateAccountCredential(account.id, updated);
175
+ debug.log('engine', `Codex: persisted refreshed auth.json snapshot to account ${account.id}`);
176
+ } catch (error) {
177
+ debug.warn('engine', 'Codex: failed to persist auth.json snapshot:', error);
178
+ }
179
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Codex SDK error handler.
3
+ *
4
+ * Mirrors the Claude / Copilot error-handler pattern:
5
+ * - Swallow abort errors (returned during cancellation, not rethrown).
6
+ * - Map well-known Codex error categories to user-facing messages.
7
+ * - Otherwise enrich the message with status code / request id when available.
8
+ */
9
+
10
+ import type { ThreadError } from '@openai/codex-sdk';
11
+
12
+ export function handleStreamError(error: unknown): void {
13
+ if (!(error instanceof Error)) {
14
+ throw error;
15
+ }
16
+
17
+ if (
18
+ error.name === 'AbortError'
19
+ || error.message.includes('aborted')
20
+ || error.message.includes('abort')
21
+ || error.message === 'Operation aborted'
22
+ ) {
23
+ return;
24
+ }
25
+
26
+ if (error.message.includes('ENOENT') || error.message.includes('spawn codex')) {
27
+ throw new Error('Codex CLI not found. Install it via Settings → System Tools (or run `bun add -g @openai/codex`).');
28
+ }
29
+
30
+ if (error.message.includes('OPENAI_API_KEY') || error.message.includes('not authenticated')) {
31
+ throw new Error('Codex is not authenticated. Add an API key or sign in with ChatGPT in Settings → Engines.');
32
+ }
33
+
34
+ if (error.message.includes('insufficient_quota') || error.message.includes('quota')) {
35
+ throw new Error('Codex quota exceeded. Add credits to your OpenAI account or switch to a ChatGPT-mode account.');
36
+ }
37
+
38
+ if (error.message.includes('401') || error.message.toLowerCase().includes('unauthorized')) {
39
+ throw new Error('Codex authentication failed. Re-authenticate in Settings → Engines.');
40
+ }
41
+
42
+ throw new Error(extractDetailedError(error));
43
+ }
44
+
45
+ /**
46
+ * Build a Codex-flavoured error from a `turn.failed` event payload.
47
+ */
48
+ export function buildTurnError(data: ThreadError): Error {
49
+ return new Error(data.message?.trim() || 'Unknown Codex error');
50
+ }
51
+
52
+ function extractDetailedError(error: Error): string {
53
+ const err = error as unknown as Record<string, unknown>;
54
+ let message = (typeof err.message === 'string' ? err.message : '').replace(/^Error:\s*/, '');
55
+ if (!message) {
56
+ message = typeof err.name === 'string' && err.name !== 'Error' ? err.name : 'Unknown error';
57
+ }
58
+ if (err.status && !message.includes(String(err.status))) {
59
+ message += ` (status ${String(err.status)})`;
60
+ }
61
+ if (err.code && !message.includes(String(err.code))) {
62
+ message += ` [${String(err.code)}]`;
63
+ }
64
+ return message || error.message || 'Unknown error';
65
+ }
@@ -0,0 +1 @@
1
+ export { CodexEngine } from './stream';