@myrialabs/clopen 0.3.14 → 0.3.16

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.
@@ -393,19 +393,20 @@ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
393
393
  /**
394
394
  * Convert SDKTaskNotificationMessage (terminal background-task event) →
395
395
  * NotificationEvent. Fires when a backgrounded Agent/teammate finishes
396
- * (status completed | failed | stopped). The non-terminal task_started /
397
- * task_progress / task_updated messages are intentionally not surfaced —
398
- * they would spam the toast and there is no dedicated tasks panel.
396
+ * abnormally (failed | stopped). Successful completion is intentionally
397
+ * not surfaced — the result already lands in the conversation, and a
398
+ * success toast is just noise. The non-terminal task_started /
399
+ * task_progress / task_updated messages are also not surfaced.
399
400
  */
400
401
  function convertTaskNotification(
401
402
  msg: { session_id: string; status: string; summary?: string; task_id: string },
402
- ): NotificationEvent {
403
- const completed = msg.status === 'completed';
403
+ ): NotificationEvent | null {
404
+ if (msg.status === 'completed') return null;
404
405
  return {
405
406
  type: 'notification',
406
407
  sessionId: msg.session_id,
407
- level: completed ? 'info' : 'warning',
408
- title: completed ? 'Background task completed' : `Background task ${msg.status}`,
408
+ level: 'warning',
409
+ title: `Background task ${msg.status}`,
409
410
  message: msg.summary || `Task ${msg.task_id} ${msg.status}`,
410
411
  };
411
412
  }
@@ -507,7 +508,8 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
507
508
  } else if (subtype === 'compact_boundary') {
508
509
  yield convertCompactBoundary(msg as SDKCompactBoundaryMessage);
509
510
  } else if (subtype === 'task_notification') {
510
- yield convertTaskNotification(msg as unknown as Parameters<typeof convertTaskNotification>[0]);
511
+ const note = convertTaskNotification(msg as unknown as Parameters<typeof convertTaskNotification>[0]);
512
+ if (note) yield note;
511
513
  }
512
514
  // task_started / task_progress / task_updated: background-task
513
515
  // progress noise — intentionally not surfaced (no tasks panel).
@@ -14,8 +14,8 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
14
14
  type: 'claude-code',
15
15
  provider: 'anthropic',
16
16
  model: {
17
- id: 'claude-opus-4-7',
18
- name: 'Claude Opus 4.7',
17
+ id: 'claude-opus-4-8',
18
+ name: 'Claude Opus 4.8',
19
19
  },
20
20
  account: {
21
21
  id: 0,
@@ -138,6 +138,49 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
138
138
  output: 5,
139
139
  },
140
140
  },
141
+ {
142
+ engine: {
143
+ type: 'claude-code',
144
+ provider: 'anthropic',
145
+ model: {
146
+ id: 'claude-opus-4-7',
147
+ name: 'Claude Opus 4.7',
148
+ },
149
+ account: {
150
+ id: 0,
151
+ name: '',
152
+ },
153
+ },
154
+ limit: {
155
+ input: 1_000_000,
156
+ output: 128_000,
157
+ },
158
+ modalities: {
159
+ input: {
160
+ text: true,
161
+ image: true,
162
+ audio: false,
163
+ video: false,
164
+ pdf: true,
165
+ },
166
+ output: {
167
+ text: true,
168
+ image: false,
169
+ audio: false,
170
+ video: false,
171
+ pdf: false,
172
+ },
173
+ },
174
+ capabilities: {
175
+ reasoning: true,
176
+ tools: true,
177
+ structuredOutput: true,
178
+ },
179
+ cost: {
180
+ input: 5,
181
+ output: 25,
182
+ },
183
+ },
141
184
  {
142
185
  engine: {
143
186
  type: 'claude-code',
@@ -123,7 +123,6 @@ export class CopilotEngine implements AIEngine {
123
123
  this.client = new CopilotClient({
124
124
  gitHubToken: account.credential,
125
125
  useLoggedInUser: false,
126
- autoStart: true,
127
126
  });
128
127
 
129
128
  await this.client.start();
@@ -1,21 +1,9 @@
1
1
  import { join, extname } from 'path';
2
+ import { readdir } from 'node:fs/promises';
2
3
  import { readFileWithEncoding, isTextFile } from '$shared/utils/file-type-detection';
3
4
 
4
5
  import { debug } from '$shared/utils/logger';
5
6
 
6
- // Bun-compatible readdir implementation (cross-platform)
7
- async function readdir(path: string): Promise<string[]> {
8
- let proc;
9
- if (process.platform === 'win32') {
10
- proc = Bun.spawn(['cmd', '/c', 'dir', '/b', '/a', path], { stdout: 'pipe', stderr: 'ignore' });
11
- } else {
12
- proc = Bun.spawn(['ls', '-1A', path], { stdout: 'pipe', stderr: 'ignore' });
13
- }
14
- const result = await new Response(proc.stdout).text();
15
- // Split and clean up, removing \r characters for Windows compatibility
16
- return result.trim().split(/\r?\n/).map(line => line.trim()).filter(Boolean);
17
- }
18
-
19
7
  // Return types
20
8
  export interface FileTreeNode {
21
9
  name: string;
@@ -0,0 +1,236 @@
1
+ /**
2
+ * HTTP routes for per-user custom notification sounds.
3
+ *
4
+ * Storage layout: ~/.clopen[-dev]/audio/<userId>/notification.<ext>
5
+ * One file per user — uploading replaces any previous file (including different ext).
6
+ *
7
+ * Auth: `Authorization: Bearer <session-token>` (same token issued by auth:login).
8
+ */
9
+
10
+ import { Elysia } from 'elysia';
11
+ import { join } from 'node:path';
12
+ import { mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
13
+
14
+ import { debug } from '$shared/utils/logger';
15
+ import { hashToken } from '../auth/tokens';
16
+ import { authQueries } from '../database/queries';
17
+ import { getClopenDir } from '../utils/paths';
18
+ import {
19
+ NOTIFICATION_SOUND_ALLOWED_EXTS,
20
+ NOTIFICATION_SOUND_MAX_BYTES,
21
+ isValidNotificationSoundExt
22
+ } from '$shared/constants/notification-sounds';
23
+
24
+ type AuthIdentity = { userId: string; role: string };
25
+
26
+ function authenticate(request: Request): AuthIdentity {
27
+ const header = request.headers.get('authorization') || request.headers.get('Authorization');
28
+ if (!header || !header.toLowerCase().startsWith('bearer ')) {
29
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
30
+ }
31
+ const token = header.slice(7).trim();
32
+ if (!token) {
33
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
34
+ }
35
+ const session = authQueries.getSessionByTokenHash(hashToken(token));
36
+ if (!session) {
37
+ throw Object.assign(new Error('Invalid session token'), { status: 401 });
38
+ }
39
+ if (new Date(session.expires_at) < new Date()) {
40
+ throw Object.assign(new Error('Session expired'), { status: 401 });
41
+ }
42
+ const user = authQueries.getUserById(session.user_id);
43
+ if (!user) {
44
+ throw Object.assign(new Error('User not found'), { status: 401 });
45
+ }
46
+ authQueries.updateLastActive(session.id);
47
+ return { userId: user.id, role: user.role };
48
+ }
49
+
50
+ function getUserAudioDir(userId: string): string {
51
+ return join(getClopenDir(), 'audio', userId);
52
+ }
53
+
54
+ const EXT_CONTENT_TYPES: Record<string, string> = {
55
+ mp3: 'audio/mpeg',
56
+ ogg: 'audio/ogg',
57
+ wav: 'audio/wav',
58
+ m4a: 'audio/mp4'
59
+ };
60
+
61
+ async function findExistingCustomFile(dir: string): Promise<{ path: string; ext: string } | null> {
62
+ let entries: string[];
63
+ try {
64
+ entries = await readdir(dir);
65
+ } catch {
66
+ return null;
67
+ }
68
+ for (const ext of NOTIFICATION_SOUND_ALLOWED_EXTS) {
69
+ const name = `notification.${ext}`;
70
+ if (entries.includes(name)) {
71
+ return { path: join(dir, name), ext };
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export const audioRoute = new Elysia()
78
+ .post('/api/audio/upload', async ({ request, query }) => {
79
+ let identity: AuthIdentity;
80
+ try {
81
+ identity = authenticate(request);
82
+ } catch (error) {
83
+ const status = (error as { status?: number }).status ?? 401;
84
+ const message = error instanceof Error ? error.message : 'Unauthorized';
85
+ return new Response(message, { status });
86
+ }
87
+
88
+ const extParam = typeof query.ext === 'string' ? query.ext.toLowerCase() : '';
89
+ const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
90
+
91
+ if (!isValidNotificationSoundExt(extParam)) {
92
+ return new Response(
93
+ `Unsupported audio format. Allowed: ${NOTIFICATION_SOUND_ALLOWED_EXTS.join(', ')}`,
94
+ { status: 400 }
95
+ );
96
+ }
97
+ if (!Number.isFinite(fileSizeParam) || fileSizeParam <= 0) {
98
+ return new Response('Invalid fileSize query parameter', { status: 400 });
99
+ }
100
+ if (fileSizeParam > NOTIFICATION_SOUND_MAX_BYTES) {
101
+ return new Response(
102
+ `File too large. Max ${NOTIFICATION_SOUND_MAX_BYTES} bytes (${Math.round(NOTIFICATION_SOUND_MAX_BYTES / 1024)} KB)`,
103
+ { status: 413 }
104
+ );
105
+ }
106
+ if (!request.body) {
107
+ return new Response('Request body is empty', { status: 400 });
108
+ }
109
+
110
+ const userDir = getUserAudioDir(identity.userId);
111
+ await mkdir(userDir, { recursive: true });
112
+
113
+ const finalPath = join(userDir, `notification.${extParam}`);
114
+ const tempPath = `${finalPath}.${crypto.randomUUID()}.partial`;
115
+ const writer = Bun.file(tempPath).writer();
116
+ let written = 0;
117
+
118
+ const cleanupTemp = async () => {
119
+ try { await writer.end(); } catch { /* best-effort */ }
120
+ try { await unlink(tempPath); } catch { /* best-effort */ }
121
+ };
122
+
123
+ try {
124
+ const reader = request.body.getReader();
125
+ while (true) {
126
+ const { done, value } = await reader.read();
127
+ if (done) break;
128
+ if (!value) continue;
129
+ const incoming = value.byteLength;
130
+ if (written + incoming > fileSizeParam) {
131
+ await cleanupTemp();
132
+ return new Response('Received more bytes than declared file size', { status: 400 });
133
+ }
134
+ if (written + incoming > NOTIFICATION_SOUND_MAX_BYTES) {
135
+ await cleanupTemp();
136
+ return new Response('File too large', { status: 413 });
137
+ }
138
+ writer.write(value);
139
+ written += incoming;
140
+ }
141
+
142
+ await writer.end();
143
+
144
+ if (written !== fileSizeParam) {
145
+ await unlink(tempPath).catch(() => {});
146
+ return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, {
147
+ status: 400
148
+ });
149
+ }
150
+
151
+ // Remove any previously-uploaded file with a different extension.
152
+ const existing = await findExistingCustomFile(userDir);
153
+ if (existing && existing.path !== finalPath) {
154
+ await unlink(existing.path).catch(() => {});
155
+ }
156
+
157
+ await rename(tempPath, finalPath);
158
+ const stats = await stat(finalPath);
159
+
160
+ return Response.json({
161
+ message: 'Sound uploaded successfully',
162
+ ext: extParam,
163
+ size: stats.size,
164
+ modified: stats.mtime.toISOString()
165
+ });
166
+ } catch (error) {
167
+ await cleanupTemp();
168
+ debug.error('notification', 'HTTP audio upload error:', error);
169
+ const message = error instanceof Error ? error.message : 'Upload failed';
170
+ return new Response(message, { status: 500 });
171
+ }
172
+ })
173
+ .get('/api/audio/custom/meta', async ({ request }) => {
174
+ let identity: AuthIdentity;
175
+ try {
176
+ identity = authenticate(request);
177
+ } catch (error) {
178
+ const status = (error as { status?: number }).status ?? 401;
179
+ const message = error instanceof Error ? error.message : 'Unauthorized';
180
+ return new Response(message, { status });
181
+ }
182
+
183
+ const userDir = getUserAudioDir(identity.userId);
184
+ const existing = await findExistingCustomFile(userDir);
185
+ if (!existing) {
186
+ return Response.json({ exists: false });
187
+ }
188
+ const stats = await stat(existing.path).catch(() => null);
189
+ return Response.json({
190
+ exists: true,
191
+ ext: existing.ext,
192
+ size: stats?.size ?? 0,
193
+ modified: stats?.mtime.toISOString() ?? null
194
+ });
195
+ })
196
+ .get('/api/audio/custom', async ({ request }) => {
197
+ let identity: AuthIdentity;
198
+ try {
199
+ identity = authenticate(request);
200
+ } catch (error) {
201
+ const status = (error as { status?: number }).status ?? 401;
202
+ const message = error instanceof Error ? error.message : 'Unauthorized';
203
+ return new Response(message, { status });
204
+ }
205
+
206
+ const userDir = getUserAudioDir(identity.userId);
207
+ const existing = await findExistingCustomFile(userDir);
208
+ if (!existing) {
209
+ return new Response('No custom sound', { status: 404 });
210
+ }
211
+
212
+ const file = Bun.file(existing.path);
213
+ return new Response(file, {
214
+ headers: {
215
+ 'Content-Type': EXT_CONTENT_TYPES[existing.ext] ?? 'application/octet-stream',
216
+ 'Cache-Control': 'no-cache'
217
+ }
218
+ });
219
+ })
220
+ .delete('/api/audio/custom', async ({ request }) => {
221
+ let identity: AuthIdentity;
222
+ try {
223
+ identity = authenticate(request);
224
+ } catch (error) {
225
+ const status = (error as { status?: number }).status ?? 401;
226
+ const message = error instanceof Error ? error.message : 'Unauthorized';
227
+ return new Response(message, { status });
228
+ }
229
+
230
+ const userDir = getUserAudioDir(identity.userId);
231
+ const existing = await findExistingCustomFile(userDir);
232
+ if (existing) {
233
+ await unlink(existing.path).catch(() => {});
234
+ }
235
+ return Response.json({ message: 'Custom sound removed' });
236
+ });
package/backend/index.ts CHANGED
@@ -32,6 +32,9 @@ import { wsRouter } from './ws';
32
32
  // binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
33
33
  import { filesUploadRoute } from './http/files-upload';
34
34
 
35
+ // HTTP routes for per-user notification sounds (upload / serve / delete).
36
+ import { audioRoute } from './http/audio';
37
+
35
38
  // Import browser preview manager for graceful shutdown
36
39
  import { browserPreviewServiceManager } from './preview';
37
40
 
@@ -100,6 +103,9 @@ const app = new Elysia()
100
103
  // stays on the HTTP path through the Vite dev proxy.
101
104
  .use(filesUploadRoute)
102
105
 
106
+ // Per-user notification sound upload/serve/delete.
107
+ .use(audioRoute)
108
+
103
109
  // Mount WebSocket router (all functionality now via WebSocket)
104
110
  .use(wsRouter.asPlugin('/ws'));
105
111
 
@@ -18,5 +18,7 @@ export {
18
18
  type DeleteTunnelOptions,
19
19
  type DeleteTunnelResult,
20
20
  type RouteDnsOptions,
21
- type RouteDnsResult
21
+ type RouteDnsResult,
22
+ type ListTunnelsOptions,
23
+ type TunnelListEntry
22
24
  } from './tunnel';
@@ -106,6 +106,17 @@ export interface RouteDnsResult {
106
106
  output: string;
107
107
  }
108
108
 
109
+ export interface ListTunnelsOptions {
110
+ /** Custom path for the origin certificate */
111
+ origincert?: string;
112
+ }
113
+
114
+ export interface TunnelListEntry {
115
+ id: string;
116
+ name: string;
117
+ connections: unknown[];
118
+ }
119
+
109
120
  type OutputHandler = (output: string, tunnel: CloudflaredTunnel) => void;
110
121
 
111
122
  export class CloudflaredTunnel extends EventEmitter {
@@ -288,6 +299,37 @@ export class CloudflaredTunnel extends EventEmitter {
288
299
  throw new Error(`Failed to route DNS: ${output.trim()}`);
289
300
  }
290
301
 
302
+ /** List all tunnels on the authenticated Cloudflare account. */
303
+ static async listTunnels(options?: ListTunnelsOptions): Promise<TunnelListEntry[]> {
304
+ const args = ['tunnel'];
305
+ if (options?.origincert) args.push('--origincert', options.origincert);
306
+ args.push('list', '--output', 'json');
307
+
308
+ const { output, exitCode } = await CloudflaredTunnel.run(args);
309
+
310
+ if (exitCode !== 0) {
311
+ throw new Error(`Failed to list tunnels: ${output.trim()}`);
312
+ }
313
+
314
+ // cloudflared prints warnings (e.g. outdated-version notice) alongside the
315
+ // JSON array, so isolate the array span before parsing.
316
+ const start = output.indexOf('[');
317
+ const end = output.lastIndexOf(']');
318
+ if (start === -1 || end === -1 || end < start) return [];
319
+
320
+ try {
321
+ const parsed = JSON.parse(output.slice(start, end + 1));
322
+ if (!Array.isArray(parsed)) return [];
323
+ return parsed.map((entry) => ({
324
+ id: String(entry.id),
325
+ name: String(entry.name),
326
+ connections: Array.isArray(entry.connections) ? entry.connections : []
327
+ }));
328
+ } catch {
329
+ return [];
330
+ }
331
+ }
332
+
291
333
  // --- Private helpers ---
292
334
 
293
335
  /** Run a one-shot cloudflared command and collect all output. */
@@ -11,7 +11,7 @@ import { debug } from '$shared/utils/logger';
11
11
  import { existsSync, mkdirSync, renameSync, writeFileSync, unlinkSync, rmSync } from 'fs';
12
12
  import { homedir } from 'os';
13
13
  import { join } from 'path';
14
- import { getTunnelDir } from './tunnel-config';
14
+ import { getTunnelDir, getLocalTunnelConfigs } from './tunnel-config';
15
15
  import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
16
16
  import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError, type LoginHandle } from './cloudflared';
17
17
 
@@ -57,6 +57,11 @@ interface LocalTunnelInstance extends BaseTunnelInstance {
57
57
  const CERT_PATH = join(getTunnelDir(), 'cert.pem');
58
58
  const DEFAULT_CLOUDFLARED_CERT = join(homedir(), '.cloudflared', 'cert.pem');
59
59
 
60
+ function isTunnelNameConflict(error: unknown): boolean {
61
+ const message = error instanceof Error ? error.message : String(error);
62
+ return /tunnel with name already exists/i.test(message);
63
+ }
64
+
60
65
  // --- Manager ---
61
66
 
62
67
  class GlobalTunnelManager {
@@ -395,6 +400,19 @@ class GlobalTunnelManager {
395
400
  async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
396
401
  this.ensureBinaryAvailable();
397
402
 
403
+ try {
404
+ return await this.runCreateLocalTunnel(name);
405
+ } catch (error) {
406
+ if (!isTunnelNameConflict(error)) throw error;
407
+
408
+ // Name collides on Cloudflare. Auto-recover only when it's a true orphan,
409
+ // then retry once. Anything else surfaces a clear, actionable message.
410
+ await this.resolveTunnelNameConflict(name);
411
+ return await this.runCreateLocalTunnel(name);
412
+ }
413
+ }
414
+
415
+ private async runCreateLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
398
416
  // Write credentials directly to our dir (not ~/.cloudflared/)
399
417
  const tunnelBaseDir = getTunnelDir();
400
418
  if (!existsSync(tunnelBaseDir)) {
@@ -415,6 +433,39 @@ class GlobalTunnelManager {
415
433
  return { tunnelId: result.tunnelId, credentialsFile: finalCredentials };
416
434
  }
417
435
 
436
+ /**
437
+ * Handle a "tunnel with name already exists" conflict. A tunnel that exists on
438
+ * Cloudflare but isn't tracked locally and has no active connections is an orphan
439
+ * (usually a half-failed create) and is safe to delete so the create can retry.
440
+ * Everything else throws a clear message instead.
441
+ */
442
+ private async resolveTunnelNameConflict(name: string): Promise<void> {
443
+ let existing;
444
+ try {
445
+ existing = await CloudflaredTunnel.listTunnels({ origincert: CERT_PATH });
446
+ } catch (listError) {
447
+ debug.warn('tunnel', 'Could not list tunnels to resolve name conflict:', listError);
448
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
449
+ }
450
+
451
+ const match = existing.find((t) => t.name === name);
452
+ if (!match) {
453
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
454
+ }
455
+
456
+ if (getLocalTunnelConfigs().some((c) => c.tunnelId === match.id)) {
457
+ throw new Error(`A tunnel named "${name}" already exists. Choose a different name, or delete the existing tunnel first.`);
458
+ }
459
+
460
+ if (match.connections.length > 0) {
461
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists and has active connections. Choose a different name, or remove it from the Cloudflare dashboard.`);
462
+ }
463
+
464
+ debug.warn('tunnel', `Orphaned tunnel "${name}" (${match.id}) found on Cloudflare; deleting before recreate`);
465
+ await CloudflaredTunnel.deleteTunnel(match.id, { force: true, origincert: CERT_PATH });
466
+ this.cleanupLocalTunnelFiles(match.id);
467
+ }
468
+
418
469
  async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
419
470
  this.ensureBinaryAvailable();
420
471
 
@@ -149,6 +149,7 @@ interface CodeMatch {
149
149
  line: number;
150
150
  text: string;
151
151
  column: number;
152
+ length: number;
152
153
  }
153
154
 
154
155
  interface CodeSearchResult {
@@ -231,7 +232,8 @@ async function searchCodeContent(
231
232
  matches.push({
232
233
  line: i + 1,
233
234
  text: lines[i].trimEnd(),
234
- column: match.index + 1
235
+ column: match.index + 1,
236
+ length: match[0].length
235
237
  });
236
238
  // Prevent infinite loop for zero-length matches
237
239
  if (match[0].length === 0) {
@@ -378,7 +380,8 @@ export const fileSearchHandler = createRouter()
378
380
  matches: t.Array(t.Object({
379
381
  line: t.Number(),
380
382
  text: t.String(),
381
- column: t.Number()
383
+ column: t.Number(),
384
+ length: t.Number()
382
385
  })),
383
386
  totalMatches: t.Number()
384
387
  }))
@@ -23,7 +23,7 @@ import {
23
23
  deleteOperation
24
24
  } from '../../files/file-operations';
25
25
  import { createZipOperation, extractZipOperation } from '../../files/file-archive';
26
- import { stat as fsStat, readdir as fsReaddir, rename as fsRename, access as fsAccess } from 'node:fs/promises';
26
+ import { stat as fsStat, readdir as fsReaddir, rename as fsRename } from 'node:fs/promises';
27
27
  import { requireFilePathAccess, requireSharedFilePathAccess } from './path-access';
28
28
 
29
29
  export const writeHandler = createRouter()
@@ -241,14 +241,21 @@ export const writeHandler = createRouter()
241
241
  throw new Error('Source path is not a directory');
242
242
  }
243
243
 
244
+ // Reject only when the destination is a genuinely different entry. On
245
+ // case-insensitive filesystems (default on macOS and Windows) a
246
+ // case-only rename like "Foo" -> "foo" makes the destination resolve to
247
+ // the same inode as the source, so allow that case through.
244
248
  try {
245
- await fsAccess(newPath);
246
- throw new Error('Destination path already exists');
249
+ const newStats = await fsStat(newPath);
250
+ const sameEntry = newStats.ino === oldStats.ino && newStats.dev === oldStats.dev;
251
+ if (!sameEntry) {
252
+ throw new Error('Destination path already exists');
253
+ }
247
254
  } catch (err) {
248
255
  if (err instanceof Error && err.message === 'Destination path already exists') {
249
256
  throw err;
250
257
  }
251
- // fsAccess threw because newPath does not exist — that is what we want.
258
+ // fsStat threw because newPath does not exist — that is what we want.
252
259
  }
253
260
 
254
261
  await fsRename(oldPath, newPath);