@myrialabs/clopen 0.4.3 → 0.4.4

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.
@@ -87,6 +87,31 @@ function classifyUnauthorized(res: Response): McpHealth {
87
87
  return { state: 'needs_config', message: 'A credential (API key / token) is required' };
88
88
  }
89
89
 
90
+ /** Cap on captured stderr so a chatty subprocess can't balloon memory. */
91
+ const STDERR_CAP = 4000;
92
+
93
+ /** Drain a subprocess's stderr into a bounded string (best-effort). */
94
+ async function drainStderr(stream: ReadableStream<Uint8Array>): Promise<string> {
95
+ const reader = stream.getReader();
96
+ const decoder = new TextDecoder();
97
+ let text = '';
98
+ try {
99
+ while (text.length < STDERR_CAP) {
100
+ const { done, value } = await reader.read();
101
+ if (done) break;
102
+ text += decoder.decode(value, { stream: true });
103
+ }
104
+ } catch { /* stream closed/cancelled */ } finally {
105
+ reader.cancel().catch(() => undefined);
106
+ }
107
+ return text;
108
+ }
109
+
110
+ /** Condense captured stderr into a short, single-line diagnostic. */
111
+ function stderrTail(text: string): string {
112
+ return text.replace(/\s+/g, ' ').trim().slice(0, 300);
113
+ }
114
+
90
115
  /**
91
116
  * Spawn a stdio server and run the same handshake over its stdin/stdout
92
117
  * (newline-delimited JSON-RPC) so "local" servers report a real connection
@@ -100,13 +125,18 @@ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
100
125
  proc = Bun.spawn([s.command, ...s.args], {
101
126
  stdin: 'pipe',
102
127
  stdout: 'pipe',
103
- stderr: 'ignore',
128
+ stderr: 'pipe',
104
129
  env: { ...process.env, ...s.env }
105
130
  });
106
131
  } catch (error) {
107
132
  return { state: 'unreachable', message: error instanceof Error ? error.message : 'Failed to start command' };
108
133
  }
109
134
 
135
+ // Capture stderr concurrently so a process that prints usage/errors and then
136
+ // exits (e.g. a CLI that needs a `mcp` subcommand to actually start the
137
+ // server) yields an actionable message instead of a misleading timeout.
138
+ const stderrPromise = drainStderr(proc.stderr as unknown as ReadableStream<Uint8Array>);
139
+
110
140
  try {
111
141
  const stdin = proc.stdin as unknown as { write(data: Uint8Array): number; flush?(): Promise<number> | number };
112
142
  const stdout = proc.stdout as unknown as ReadableStream<Uint8Array>;
@@ -117,10 +147,30 @@ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
117
147
  await stdin.flush?.();
118
148
 
119
149
  const rpc = await readStdoutForId(stdout, 2, STDIO_PROBE_TIMEOUT_MS);
120
- if (!rpc) return { state: 'unreachable', message: `No response within ${STDIO_PROBE_TIMEOUT_MS / 1000}s` };
121
- if (Array.isArray(rpc.result?.tools)) return { state: 'ok', toolCount: rpc.result.tools.length };
122
- const detail = rpc.error?.message ?? 'Server did not return a tool list';
123
- return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
150
+ if (rpc) {
151
+ if (Array.isArray(rpc.result?.tools)) return { state: 'ok', toolCount: rpc.result.tools.length };
152
+ const detail = rpc.error?.message ?? 'Server did not return a tool list';
153
+ return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
154
+ }
155
+
156
+ // No JSON-RPC reply. Distinguish a process that already exited (a real,
157
+ // reportable error — wrong command, missing subcommand, crash) from one
158
+ // that's still alive but silent (a genuine timeout).
159
+ const exitCode = await Promise.race([
160
+ proc.exited,
161
+ new Promise<number | null>(resolve => setTimeout(() => resolve(null), 250))
162
+ ]);
163
+ if (exitCode !== null) {
164
+ const tail = stderrTail(await Promise.race([
165
+ stderrPromise,
166
+ new Promise<string>(resolve => setTimeout(() => resolve(''), 200))
167
+ ]));
168
+ const detail = tail
169
+ ? `Process exited (code ${exitCode}): ${tail}`
170
+ : `Process exited (code ${exitCode}) before responding`;
171
+ return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
172
+ }
173
+ return { state: 'unreachable', message: `No response within ${STDIO_PROBE_TIMEOUT_MS / 1000}s` };
124
174
  } catch (error) {
125
175
  return { state: 'error', message: error instanceof Error ? error.message : 'Probe failed' };
126
176
  } finally {
@@ -109,7 +109,14 @@ function resolveStdioPackage(pkg: RegistryPackage): { command: string; args: str
109
109
  if (!command || !pkg.identifier) return null;
110
110
 
111
111
  const args: string[] = [];
112
- for (const a of pkg.runtimeArguments ?? []) args.push(...argTokens(a));
112
+ const runtimeArgs = pkg.runtimeArguments ?? [];
113
+ // `npx` prompts before fetching an uncached package; `-y` keeps the
114
+ // non-interactive spawn (health probe + engine) from stalling on that prompt.
115
+ // Skip if the registry already supplies a confirm flag.
116
+ if (/(^|\/)npx$/.test(command) && !runtimeArgs.some(a => a.name === '-y' || a.name === '--yes')) {
117
+ args.push('-y');
118
+ }
119
+ for (const a of runtimeArgs) args.push(...argTokens(a));
113
120
 
114
121
  // Package identifier token (with version for npm-style registries).
115
122
  const identifier = pkg.version && pkg.registryType === 'npm'
@@ -10,6 +10,22 @@ export function getClopenDir(): string {
10
10
  return join(homedir(), process.env.NODE_ENV === 'development' ? '.clopen-dev' : '.clopen');
11
11
  }
12
12
 
13
+ /**
14
+ * Returns the isolated per-engine config/home directory under
15
+ * `{clopenDir}/engine/{engine}/user/`.
16
+ *
17
+ * Every engine's runtime state (credentials, sessions, logs) is redirected
18
+ * here via that engine's home/config env var (CLAUDE_CONFIG_DIR, CODEX_HOME,
19
+ * COPILOT_HOME, QWEN_RUNTIME_DIR, XDG_* for OpenCode) so Clopen never mixes
20
+ * its data with the user's own global CLI usage (~/.codex, ~/.copilot, …).
21
+ *
22
+ * Grouped under an `engine/` parent so all AI-engine state sits in one place,
23
+ * separate from Clopen's other data dirs (snapshots, etc.).
24
+ */
25
+ export function getEngineUserConfigDir(engine: string): string {
26
+ return join(getClopenDir(), 'engine', engine, 'user');
27
+ }
28
+
13
29
  /**
14
30
  * Resolve a path to an OS-native absolute path.
15
31
  * On Windows: resolves relative paths, prepends drive letter, converts to backslashes.
@@ -46,6 +46,7 @@ import {
46
46
  applyAccountAuth,
47
47
  readAuthJson,
48
48
  serializeCodexCredential,
49
+ getCodexHomeDir,
49
50
  } from '../../../engine/adapters/codex/credential';
50
51
  import { resolveBinaryWithRefresh } from '../../../utils/cli';
51
52
  import { getCleanSpawnEnv } from '../../../utils/env';
@@ -324,6 +325,8 @@ export const codexAccountsHandler = createRouter()
324
325
  // server. (`BROWSER=false` is honoured by most OS open helpers.)
325
326
  const ptyEnv = getCleanSpawnEnv();
326
327
  ptyEnv['BROWSER'] = 'false';
328
+ // Write auth.json into Clopen's isolated Codex home, not ~/.codex.
329
+ ptyEnv['CODEX_HOME'] = getCodexHomeDir();
327
330
 
328
331
  let pty: ReturnType<typeof spawn>;
329
332
  try {
@@ -199,7 +199,11 @@ export const mcpCrudHandler = createRouter()
199
199
  data: t.Object({
200
200
  id: t.Number(),
201
201
  env: t.Optional(t.Record(t.String(), t.String())),
202
- headers: t.Optional(t.Record(t.String(), t.String()))
202
+ headers: t.Optional(t.Record(t.String(), t.String())),
203
+ // stdio only: repair an incomplete registry command (e.g. a missing
204
+ // `mcp` subcommand). Ignored for remote servers.
205
+ command: t.Optional(t.String()),
206
+ args: t.Optional(t.Array(t.String()))
203
207
  }),
204
208
  response: t.Object({ server: INSTALLED_SERVER_SCHEMA })
205
209
  }, async ({ data }) => {
@@ -216,6 +220,13 @@ export const mcpCrudHandler = createRouter()
216
220
  try { configSchema = JSON.parse(existing.config_schema); } catch { /* ignore */ }
217
221
  assertRequiredConfig(configSchema, env, headers);
218
222
  mcpServerQueries.updateConfig(data.id, env, headers);
223
+ // Persist an edited command/args for stdio servers (drop blank arg tokens).
224
+ if (existing.transport === 'stdio' && (data.command !== undefined || data.args !== undefined)) {
225
+ const command = (data.command ?? existing.command ?? '').trim();
226
+ if (!command) throw new Error('A stdio MCP server requires a command');
227
+ const args = (data.args ?? []).map(a => a.trim()).filter(a => a !== '');
228
+ mcpServerQueries.updateCommand(data.id, command, args);
229
+ }
219
230
  debug.log('mcp', `🔧 Updated config for external MCP server: ${existing.slug}`);
220
231
  return { server: toDTO(mcpServerQueries.getById(data.id)!) };
221
232
  })