@myrialabs/clopen 0.4.5 → 0.4.7

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 (58) hide show
  1. package/backend/auth/permissions.ts +14 -1
  2. package/backend/auth/session-invalidation.test.ts +17 -21
  3. package/backend/auth/session-invalidation.ts +10 -11
  4. package/backend/database/migrations/044_create_skills_table.ts +29 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/index.ts +3 -1
  7. package/backend/database/queries/skill-queries.ts +105 -0
  8. package/backend/engine/adapters/claude/models.ts +46 -3
  9. package/backend/engine/adapters/claude/stream.ts +5 -0
  10. package/backend/engine/adapters/codex/credential.ts +114 -13
  11. package/backend/engine/adapters/codex/stream.ts +34 -8
  12. package/backend/engine/adapters/copilot/stream.ts +4 -0
  13. package/backend/engine/adapters/opencode/stream.ts +4 -0
  14. package/backend/engine/adapters/qwen/stream.ts +3 -0
  15. package/backend/engine/docs/lessons-learned.md +54 -50
  16. package/backend/files/file-archive.test.ts +86 -26
  17. package/backend/files/file-archive.ts +214 -134
  18. package/backend/index.ts +10 -1
  19. package/backend/mcp/README.md +77 -24
  20. package/backend/mcp/external/config.ts +82 -101
  21. package/backend/mcp/external/proxy.ts +202 -0
  22. package/backend/mcp/index.ts +4 -3
  23. package/backend/mcp/internal/remote-server.ts +103 -55
  24. package/backend/skills/index.ts +21 -0
  25. package/backend/skills/marketplace.ts +172 -0
  26. package/backend/skills/service.ts +245 -0
  27. package/backend/skills/spec.ts +214 -0
  28. package/backend/skills/store.ts +99 -0
  29. package/backend/skills/sync.ts +187 -0
  30. package/backend/terminal/index.ts +2 -5
  31. package/backend/terminal/ptykit.ts +64 -0
  32. package/backend/tunnel/tunnel-config.ts +1 -1
  33. package/backend/utils/ws.ts +14 -0
  34. package/backend/ws/files/write.ts +23 -7
  35. package/backend/ws/index.ts +5 -1
  36. package/backend/ws/projects/crud.ts +4 -4
  37. package/backend/ws/skills/catalog.ts +79 -0
  38. package/backend/ws/skills/crud.ts +123 -0
  39. package/backend/ws/skills/index.ts +15 -0
  40. package/backend/ws/system/operations.ts +23 -0
  41. package/backend/ws/terminal/index.ts +6 -33
  42. package/backend/ws/terminal/tunnel.ts +76 -0
  43. package/dist/assets/index-xrB3zcfA.js +1 -0
  44. package/dist/assets/main-BXS8bjJ6.css +1 -0
  45. package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
  46. package/dist/index.html +2 -2
  47. package/package.json +7 -11
  48. package/shared/constants/engines.ts +4 -4
  49. package/shared/utils/logger.ts +1 -0
  50. package/backend/terminal/helpers.ts +0 -14
  51. package/backend/terminal/pty-manager.ts +0 -4
  52. package/backend/terminal/pty-session-manager.ts +0 -349
  53. package/backend/terminal/stream-manager.ts +0 -300
  54. package/backend/ws/terminal/access.ts +0 -56
  55. package/backend/ws/terminal/persistence.ts +0 -145
  56. package/backend/ws/terminal/session.ts +0 -470
  57. package/backend/ws/terminal/stream.ts +0 -82
  58. package/dist/assets/main-gNUEJAC5.css +0 -1
@@ -46,6 +46,7 @@ import { handleStreamError } from './error-handler';
46
46
  import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
47
47
  import { fetchQwenModels } from './models';
48
48
  import { getQwenMcpConfig } from '../../../mcp';
49
+ import { syncSkills } from '$backend/skills';
49
50
  import { forkQwenSessionState, sessionStateExists } from './session-fork';
50
51
 
51
52
  interface PendingAskUserQuestion {
@@ -137,6 +138,8 @@ export class QwenEngine implements AIEngine {
137
138
 
138
139
  this.activeController = abortController || new AbortController();
139
140
  const resolvedProjectPath = resolveOsPath(projectPath);
141
+ // Refresh the synthetic skills preamble in the Qwen memory file.
142
+ await syncSkills('qwen');
140
143
  const mcpConfig = getQwenMcpConfig();
141
144
 
142
145
  // Fork-by-copy on EVERY resume — same semantics as Claude
@@ -727,63 +727,67 @@ event protocol. Until then, v1 is intentional.
727
727
 
728
728
  ---
729
729
 
730
- ### 9.18 External (registry) MCP servers — pass auth headers; OAuth is centralized
730
+ ### 9.18 External (registry) MCP servers — proxied through the bridge
731
731
 
732
732
  §9.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
733
- ones users install from the registry, stored in `mcp_servers`) are different:
734
- the engine connects **directly** to a third-party URL or stdio command, and
735
- many require authentication.
736
-
737
- > **Two distinct token systems — don't conflate them.** The internal bridge
738
- > uses a process-scoped, in-memory **service token** sent only over loopback
739
- > (`backend/mcp/internal/service-token.ts`, added in #363 to complete #284) —
740
- > it intentionally does **not** persist. External servers use **third-party
741
- > credentials** (OAuth tokens / API keys) that **must** persist across
742
- > restarts, so they live in the DB (`mcp_servers.oauth` / `mcp_servers.headers`).
743
- > Both happen to ride the same header fields described below.
744
-
745
- Two ways a new adapter silently breaks here:
746
-
747
- 1. **Your `getXxxExternalMcpConfig()` must forward `headers`.** Clopen is the
748
- OAuth client for remote servers (`backend/mcp/external/oauth.ts`): it runs
749
- discovery + dynamic registration + PKCE, stores tokens in
750
- `mcp_servers.oauth`, and `resolveServerRow()` injects
751
- `Authorization: Bearer <token>` into each resolved server's `headers`
752
- (alongside any static API-key header). **If your builder drops `headers`,
753
- the token never reaches the engine and every authenticated server fails
754
- with a 401 — invisibly.** Every existing builder forwards them
755
- (`getClaude/OpenCode/Copilot/QwenExternalMcpConfig`); mirror that.
756
-
757
- 2. **Use the engine's real header field — verify it, don't guess.** The field
758
- name is per-SDK and a wrong key can make the engine reject its whole
759
- config:
760
- - OpenCode / Copilot: `headers` (generic map).
761
- - Qwen: `headers` alongside `httpUrl`.
762
- - **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`.
763
- `bearer_token` is rejected for `streamable_http`
764
- (`Error loading config.toml: bearer_token is not supported for
765
- streamable_http`), which aborts the entire `codex exec` run. This mirrors
766
- the internal bridge in `backend/mcp/internal/config.ts`
767
- (`getCodexMcpConfig` → `http_headers: { Authorization: 'Bearer …' }`).
768
- When in doubt, confirm against the CLI: `codex mcp add --help`.
769
-
770
- The token is refreshed at stream start — `stream-manager` calls
771
- `refreshExpiringExternalOAuth()` before `engine.streamQuery()`, so the
772
- **synchronous** config builders below it always read a fresh access token.
773
- Do not add per-adapter OAuth flows or per-engine token stores; the engine just
774
- receives a bearer header like any other authenticated remote.
733
+ ones users install from the registry, stored in `mcp_servers`) used to be
734
+ connected **directly** by each engine — a third-party URL or stdio command.
735
+ That is no longer true: **external servers are now proxied** through a
736
+ per-server endpoint `GET/POST/DELETE /mcp/ext/<slug>` on the same
737
+ Streamable-HTTP bridge (`backend/mcp/external/proxy.ts`, mounted in
738
+ `backend/index.ts`). Clopen connects to the upstream as an MCP **client** and
739
+ re-exposes its tools; the engine only ever talks to Clopen over loopback.
740
+
741
+ > **Why proxy instead of direct?** Engines connect with the MCP SDK's
742
+ > `Client.listTools()`, which eagerly compiles an Ajv validator for every
743
+ > tool's `outputSchema`. A single unresolvable `$ref` (Stitch ships
744
+ > `#/$defs/ScreenInstance`) makes it throw, the engine CLIs' `discoverTools`
745
+ > swallow the error, and the server advertises **zero** tools while still
746
+ > reporting "connected". That hid every remote server's tools on Qwen and every
747
+ > external server on Copilot. The proxy reads `tools/list` with a **raw**
748
+ > request (no Ajv), **drops `outputSchema`**, and repairs dangling `$ref`s in
749
+ > `inputSchema` — so one bad schema can't take down a whole server.
750
+
751
+ What this means for a new adapter:
752
+
753
+ 1. **Your `getXxxExternalMcpConfig()` is a one-liner per server.** Emit a
754
+ Streamable-HTTP remote pointing at `http://localhost:<port>/mcp/ext/<slug>`
755
+ plus the **service-token** header (`getMcpServiceToken()`), in your SDK's
756
+ shape. No stdio branch, no `oauth` flags, no third-party header forwarding —
757
+ the proxy injects the upstream credential itself. Every existing builder is
758
+ now identical bar the SDK field names
759
+ (`getClaude/OpenCode/Codex/Copilot/QwenExternalMcpConfig`); mirror that.
760
+
761
+ 2. **Use the engine's real URL/header field** — same per-SDK caveats as the
762
+ internal bridge (§9.12), because the shape is identical:
763
+ - OpenCode: `url` (`type:'remote'`); Claude/Copilot: `url` (`type:'http'`).
764
+ - Qwen: `httpUrl`.
765
+ - **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`, which is
766
+ rejected for `streamable_http` and aborts the run.
767
+ - Copilot: set `tools: ['*']` so the CLI exposes the proxy's tools (its
768
+ "undefined = all" default is not honoured for dynamically discovered
769
+ servers).
770
+
771
+ > **Two token systems — don't conflate them.** The bridge (internal AND
772
+ > external endpoints) is authed by a process-scoped, in-memory **service token**
773
+ > sent only over loopback (`backend/mcp/internal/service-token.ts`). The
774
+ > **third-party credential** (OAuth token / API key, persisted in
775
+ > `mcp_servers.oauth` / `mcp_servers.headers`) is used by the **proxy**, on the
776
+ > upstream hop — never by the engine. `resolveServerRow()` injects
777
+ > `Authorization: Bearer <token>` for the proxy client; `stream-manager` calls
778
+ > `refreshExpiringExternalOAuth()` before the stream so that token is fresh.
775
779
 
776
780
  Connection health is surfaced engine-agnostically by `mcp:status`
777
- (`backend/mcp/external/probe.ts`) — it classifies `ok / needs_auth (OAuth) /
778
- needs_config (missing API key) / unreachable / error`, and the Settings panel
779
- offers **Authenticate** (OAuth) or **Configure** (API key) accordingly. A new
780
- adapter needs no work here; the probe talks to the server, not the engine.
781
+ (`backend/mcp/external/probe.ts`) — `ok / needs_auth (OAuth) / needs_config
782
+ (missing API key) / unreachable / error`. A new adapter needs no work here.
781
783
 
782
784
  What you must NOT do:
783
- - ❌ Drop `headers` from an external remote config (silent 401s).
785
+ - ❌ Point an engine straight at a third-party MCP URL/command — route it
786
+ through `/mcp/ext/<slug>` so schemas are sanitised and auth is centralized.
787
+ - ❌ Forward `mcp_servers.headers` (third-party creds) from a per-engine
788
+ builder — that's the proxy's job; the builder only carries the service token.
784
789
  - ❌ Use `bearer_token` for Codex remote MCP — use `http_headers`.
785
- - ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it and
786
- injects the bearer into every engine, Codex included.
790
+ - ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it.
787
791
 
788
792
  ---
789
793
 
@@ -1,7 +1,8 @@
1
1
  import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
- import { rm, mkdir } from 'node:fs/promises';
2
+ import { rm, mkdir, stat as fsStat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { tmpdir } from 'node:os';
5
+ import { zip, type ZipEntryInput } from '@myrialabs/zipkit';
5
6
 
6
7
  // Stub settingsQueries before importing the module under test so the file-size
7
8
  // limit is controllable and never touches a real database during unit tests.
@@ -15,7 +16,7 @@ await mock.module('../database/queries', () => ({
15
16
  }
16
17
  }));
17
18
 
18
- const { extractZipOperation } = await import('./file-archive');
19
+ const { extractArchiveOperation } = await import('./file-archive');
19
20
 
20
21
  function setLimitMB(mb: number): void {
21
22
  mockSettingsRow = {
@@ -36,11 +37,17 @@ function readU32(buf: Uint8Array, off: number): number {
36
37
  return (buf[off] | (buf[off + 1] << 8) | (buf[off + 2] << 16) | (buf[off + 3] << 24)) >>> 0;
37
38
  }
38
39
 
40
+ /** Build a ZIP fixture from a name → bytes map (single deflate method). */
41
+ async function makeZip(files: Record<string, Uint8Array>): Promise<Uint8Array> {
42
+ const entries: ZipEntryInput[] = Object.entries(files).map(([name, data]) => ({ name, data, method: 'deflate', level: 9 }));
43
+ return zip(entries);
44
+ }
45
+
39
46
  // Overwrite the uncompressed-size fields in a single-file zip's local and
40
47
  // central headers with a forged (tiny) value, leaving the compressed data and
41
48
  // compressed-size fields intact. Models an attacker lying about extracted size
42
- // to slip past any check that trusts the zip metadata. Assumes no archive
43
- // comment (true for fflate's zipSync output).
49
+ // to slip past any check that trusts the zip metadata. Assumes a single entry
50
+ // at local offset 0 and no archive comment (true for ZipKit's zip() output).
44
51
  function forgeUncompressedSizes(zip: Uint8Array, fakeSize: number): Uint8Array {
45
52
  const out = zip.slice();
46
53
  const eocd = out.length - 22;
@@ -65,19 +72,15 @@ describe('extractZipOperation — output-size cap', () => {
65
72
  });
66
73
 
67
74
  test('extracts a normal archive and writes its contents', async () => {
68
- const { zipSync } = await import('fflate');
69
- const zip = zipSync(
70
- {
71
- 'file1.txt': new TextEncoder().encode('Hello world, this is a test file'),
72
- 'file2.txt': new TextEncoder().encode('Another test file with some content')
73
- },
74
- { level: 6 }
75
- );
75
+ const archive = await makeZip({
76
+ 'file1.txt': new TextEncoder().encode('Hello world, this is a test file'),
77
+ 'file2.txt': new TextEncoder().encode('Another test file with some content')
78
+ });
76
79
  const archivePath = join(testDir, 'normal.zip');
77
80
  const extractDir = join(testDir, 'extracted');
78
- await Bun.write(archivePath, zip);
81
+ await Bun.write(archivePath, archive);
79
82
 
80
- const result = await extractZipOperation(archivePath, extractDir);
83
+ const result = await extractArchiveOperation(archivePath, extractDir);
81
84
 
82
85
  expect(result.entries).toBe(2);
83
86
  expect(await Bun.file(join(extractDir, 'file1.txt')).text()).toBe('Hello world, this is a test file');
@@ -88,14 +91,13 @@ describe('extractZipOperation — output-size cap', () => {
88
91
  // 4MB of zeros compresses to a few KB, so the compressed archive sails
89
92
  // past the compressed-size guard — only the streaming output cap catches it.
90
93
  setLimitMB(1);
91
- const { zipSync } = await import('fflate');
92
- const zip = zipSync({ 'big.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
94
+ const archive = await makeZip({ 'big.bin': new Uint8Array(4 * 1024 * 1024) });
93
95
  const archivePath = join(testDir, 'big.zip');
94
- await Bun.write(archivePath, zip);
96
+ await Bun.write(archivePath, archive);
95
97
 
96
- expect(zip.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
98
+ expect(archive.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
97
99
 
98
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
100
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
99
101
  /exceeds maximum allowed size/
100
102
  );
101
103
  });
@@ -104,8 +106,7 @@ describe('extractZipOperation — output-size cap', () => {
104
106
  // The whole point of the reshape: the cap counts ACTUAL decompressed
105
107
  // bytes, so lying about the size in the central directory cannot bypass it.
106
108
  setLimitMB(1);
107
- const { zipSync } = await import('fflate');
108
- const honest = zipSync({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
109
+ const honest = await makeZip({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) });
109
110
  const forged = forgeUncompressedSizes(honest, 10);
110
111
 
111
112
  const eocd = forged.length - 22;
@@ -115,17 +116,76 @@ describe('extractZipOperation — output-size cap', () => {
115
116
  const archivePath = join(testDir, 'forged.zip');
116
117
  await Bun.write(archivePath, forged);
117
118
 
118
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
120
  /exceeds maximum allowed size/
120
121
  );
121
122
  });
122
123
 
123
124
  test('rejects path-traversal entries before writing them', async () => {
124
- const { zipSync } = await import('fflate');
125
- const zip = zipSync({ '../escape.txt': new TextEncoder().encode('nope') }, { level: 6 });
125
+ const archive = await makeZip({ '../escape.txt': new TextEncoder().encode('nope') });
126
126
  const archivePath = join(testDir, 'traversal.zip');
127
- await Bun.write(archivePath, zip);
127
+ await Bun.write(archivePath, archive);
128
+
129
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
130
+ });
131
+ });
132
+
133
+ describe('extractArchiveOperation — encryption', () => {
134
+ let testDir: string;
135
+
136
+ beforeEach(async () => {
137
+ mockSettingsRow = null;
138
+ testDir = join(tmpdir(), `clopen-archive-enc-${Date.now()}-${Math.random().toString(36).slice(2)}`);
139
+ await mkdir(testDir, { recursive: true });
140
+ });
141
+
142
+ afterEach(async () => {
143
+ mockSettingsRow = null;
144
+ await rm(testDir, { recursive: true, force: true });
145
+ });
146
+
147
+ async function makeEncryptedZip(name: string, text: string, password: string): Promise<Uint8Array> {
148
+ return zip([{ name, data: new TextEncoder().encode(text), method: 'deflate' }], { password });
149
+ }
150
+
151
+ async function dirExists(path: string): Promise<boolean> {
152
+ try {
153
+ return (await fsStat(path)).isDirectory();
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+
159
+ test('rejects an encrypted archive when no password is given', async () => {
160
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
161
+ const archivePath = join(testDir, 'enc.zip');
162
+ const outDir = join(testDir, 'out');
163
+ await Bun.write(archivePath, archive);
164
+
165
+ await expect(extractArchiveOperation(archivePath, outDir)).rejects.toThrow(/password-protected/);
166
+ // The output folder must not be created before a valid password succeeds.
167
+ expect(await dirExists(outDir)).toBe(false);
168
+ });
169
+
170
+ test('rejects an encrypted archive with the wrong password', async () => {
171
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
172
+ const archivePath = join(testDir, 'enc-wrong.zip');
173
+ const outDir = join(testDir, 'out');
174
+ await Bun.write(archivePath, archive);
175
+
176
+ await expect(extractArchiveOperation(archivePath, outDir, 'nope')).rejects.toThrow(/[Ii]ncorrect password/);
177
+ expect(await dirExists(outDir)).toBe(false);
178
+ });
179
+
180
+ test('extracts an encrypted archive with the correct password', async () => {
181
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
182
+ const archivePath = join(testDir, 'enc-ok.zip');
183
+ const outDir = join(testDir, 'out-ok');
184
+ await Bun.write(archivePath, archive);
185
+
186
+ const result = await extractArchiveOperation(archivePath, outDir, 'hunter2');
128
187
 
129
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
188
+ expect(result.entries).toBe(1);
189
+ expect(await Bun.file(join(outDir, 'secret.txt')).text()).toBe('classified');
130
190
  });
131
191
  });