hinacode 0.2.0-alpha.2 → 0.2.0-alpha.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.
package/out/main/index.js DELETED
@@ -1,442 +0,0 @@
1
- import { existsSync, renameSync } from "node:fs";
2
- import { join, delimiter } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { Notification, nativeImage, BrowserWindow, ipcMain, app, shell, dialog, nativeTheme, protocol, safeStorage, powerMonitor, Menu, net, session } from "electron";
5
- import { h as sync, Z as catchDefect, _ as succeed, $ as callback, a0 as timeoutOrElse, a1 as seconds, a2 as TaggedError, j as String$1, a3 as promise, t as tryPromise, a4 as EVENT_CHANNEL, a5 as RPC_CHANNEL, a6 as isTrustedSender, a7 as route, a8 as map, a9 as externalUrl, v as void_, aa as catch_, ab as logWarning, g as gen, u as unsupported, E as Events, ac as runFork, r as repeat, a as spaced, f as forkScoped, U as Updates, s as suspend, e as effect, ad as ignore, z as hydratePath, ae as ATTACHMENT_PROTOCOL, af as GITHUB_ASSET_PROTOCOL, ag as PROJECT_FILE_PROTOCOL, ah as decodeUnknownOption, ai as RpcMethods, N as succeed$1, aj as Keyring, A as make$1, B as makeAppLayer, p as flatMap, ak as Environments, al as isInside, am as githubAssetId, an as GitHub, ao as projectFileRequest, ap as Files, aq as BROWSER_PARTITION, ar as LIQUID_GLASS_ARGUMENT, as as lockDownWebview, at as getOrUndefined, au as isAllowedNavigation } from "./chunks/shellPath-B4T8uBcy.js";
6
- import { createRequire } from "node:module";
7
- import { execFile, spawn } from "node:child_process";
8
- import { access } from "node:fs/promises";
9
- import { homedir } from "node:os";
10
- import { randomUUID } from "node:crypto";
11
- import updater from "electron-updater";
12
- import { join as join$1 } from "path";
13
- import "node:stream";
14
- import "node:readline";
15
- import "@anthropic-ai/claude-agent-sdk";
16
- import "node:util";
17
- import "@modelcontextprotocol/sdk/client/streamableHttp.js";
18
- import "@modelcontextprotocol/sdk/types.js";
19
- import "@muse-code/sdk";
20
- import "node:sqlite";
21
- import "node-pty";
22
- import "playwright";
23
- import "ws";
24
- import "@noble/hashes/hmac.js";
25
- import "@noble/hashes/sha2.js";
26
- import "@noble/hashes/utils.js";
27
- import "node:http";
28
- import "node:stream/promises";
29
- import "node:zlib";
30
- import "node:net";
31
- import "node:tls";
32
- const require$2 = createRequire(import.meta.url);
33
- const notificationPermission = sync(() => {
34
- if (process.platform !== "darwin") return "unknown";
35
- const { getAuthStatus } = require$2("node-mac-permissions");
36
- const status = getAuthStatus("notifications");
37
- switch (status) {
38
- case "authorized":
39
- case "provisional":
40
- return "granted";
41
- case "denied":
42
- case "restricted":
43
- return "denied";
44
- case "not determined":
45
- return "notDetermined";
46
- default:
47
- return "unknown";
48
- }
49
- }).pipe(catchDefect(() => succeed("unknown")));
50
- const askNotificationPermission = (title, body) => callback((resume) => {
51
- const notification = new Notification({ title, body, silent: true });
52
- notification.once("show", () => resume(succeed("shown")));
53
- notification.once("failed", () => resume(succeed("refused")));
54
- notification.show();
55
- }).pipe(timeoutOrElse({ duration: seconds(10), orElse: () => succeed("noAnswer") }));
56
- const launchers = {
57
- vscode: { name: "VS Code", bundle: "Visual Studio Code.app", cli: "code", opensFiles: true },
58
- cursor: { name: "Cursor", bundle: "Cursor.app", cli: "cursor", opensFiles: true },
59
- windsurf: { name: "Windsurf", bundle: "Windsurf.app", cli: "windsurf", opensFiles: true },
60
- zed: { name: "Zed", bundle: "Zed.app", cli: "zed", opensFiles: true },
61
- sublime: { name: "Sublime Text", bundle: "Sublime Text.app", cli: "subl", opensFiles: true },
62
- xcode: { name: "Xcode", bundle: "Xcode.app", cli: null, opensFiles: true },
63
- terminal: { name: "Terminal", bundle: "Utilities/Terminal.app", cli: null, opensFiles: false },
64
- iterm: { name: "iTerm", bundle: "iTerm.app", cli: null, opensFiles: false },
65
- ghostty: { name: "Ghostty", bundle: "Ghostty.app", cli: null, opensFiles: false },
66
- warp: { name: "Warp", bundle: "Warp.app", cli: null, opensFiles: false }
67
- };
68
- class OpenerError extends TaggedError()("OpenerError", { message: String$1 }) {
69
- }
70
- const exists = (path) => access(path).then(
71
- () => true,
72
- () => false
73
- );
74
- const firstExisting = async (paths) => {
75
- for (const path of paths) if (await exists(path)) return path;
76
- return null;
77
- };
78
- const applicationDirs = ["/Applications", join(homedir(), "Applications"), "/System/Applications"];
79
- const executableNames = (cli) => process.platform === "win32" ? [`${cli}.cmd`, `${cli}.exe`, cli] : [cli];
80
- const locate = (launcher) => {
81
- if (process.platform === "darwin") {
82
- const { bundle } = launcher;
83
- return bundle === null ? Promise.resolve(null) : firstExisting(applicationDirs.map((dir) => join(dir, bundle)));
84
- }
85
- const { cli } = launcher;
86
- if (cli === null) return Promise.resolve(null);
87
- const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
88
- return firstExisting(dirs.flatMap((dir) => executableNames(cli).map((name) => join(dir, name))));
89
- };
90
- const iconOf = async (location) => {
91
- if (process.platform !== "darwin") return null;
92
- const icon2 = await nativeImage.createThumbnailFromPath(location, { width: 64, height: 64 }).catch(() => null);
93
- return icon2 === null || icon2.isEmpty() ? null : icon2.toDataURL();
94
- };
95
- const listOpeners = promise(async () => {
96
- const entries = Object.entries(launchers);
97
- const found = await Promise.all(
98
- entries.map(async ([id, launcher]) => {
99
- const location = await locate(launcher);
100
- if (location === null) return null;
101
- return { id, name: launcher.name, opensFiles: launcher.opensFiles, icon: await iconOf(location) };
102
- })
103
- );
104
- return found.filter((opener) => opener !== null);
105
- });
106
- const launch = (location, path) => new Promise((resolve, reject) => {
107
- if (process.platform === "darwin") {
108
- execFile("open", ["-a", location, path], (error) => error ? reject(error) : resolve());
109
- return;
110
- }
111
- const env = { ...process.env, HINACODE_INSTANCE: void 0 };
112
- const child = process.platform === "win32" ? spawn(`"${location}"`, [`"${path}"`], { detached: true, stdio: "ignore", shell: true, env }) : spawn(location, [path], { detached: true, stdio: "ignore", env });
113
- child.once("error", reject);
114
- child.once("spawn", () => {
115
- child.unref();
116
- resolve();
117
- });
118
- });
119
- const openWith = (path, id) => tryPromise({
120
- try: async () => {
121
- const launcher = launchers[id];
122
- const location = await locate(launcher);
123
- if (location === null) throw new Error(`${launcher.name} is not installed`);
124
- await launch(location, path);
125
- },
126
- catch: (cause) => new OpenerError({ message: cause instanceof Error ? cause.message : String(cause) })
127
- });
128
- const bringToFront = (window) => {
129
- if (window.isMinimized()) window.restore();
130
- window.show();
131
- app.focus({ steal: true });
132
- window.focus();
133
- };
134
- const showOpenDialog = (window, options) => promise(() => window ? dialog.showOpenDialog(window, options) : dialog.showOpenDialog(options));
135
- const desktopCalls = (window) => ({
136
- show: sync(() => window?.show()),
137
- focus: sync(() => {
138
- if (window) bringToFront(window);
139
- }),
140
- setColorScheme: (scheme) => sync(() => {
141
- nativeTheme.themeSource = scheme;
142
- }),
143
- reveal: (path) => sync(() => shell.showItemInFolder(path)),
144
- openExternal: (url) => {
145
- const allowed = externalUrl(url);
146
- return allowed === null ? void_ : tryPromise(() => shell.openExternal(allowed)).pipe(
147
- catch_((error) => logWarning("could not open the browser", error))
148
- );
149
- },
150
- openers: listOpeners,
151
- openWith,
152
- pickFolder: map(
153
- showOpenDialog(window, { properties: ["openDirectory", "createDirectory"] }),
154
- (result) => result.canceled ? null : result.filePaths[0] ?? null
155
- ),
156
- pickFiles: map(
157
- showOpenDialog(window, { properties: ["openFile", "multiSelections"] }),
158
- (result) => result.canceled ? [] : result.filePaths
159
- ),
160
- notificationPermission,
161
- askNotificationPermission,
162
- screenOwner: window?.webContents ?? null
163
- });
164
- const untrustedSender = {
165
- error: { tag: "UntrustedSender", message: "RPC is only available to the HinaCode window" }
166
- };
167
- const registerIpc = (runtime, appUrl2) => {
168
- ipcMain.handle(
169
- RPC_CHANNEL,
170
- (event, raw) => isTrustedSender(event.senderFrame, appUrl2) ? runtime.runPromise(route(raw, desktopCalls(BrowserWindow.fromWebContents(event.sender)))) : Promise.resolve(untrustedSender)
171
- );
172
- };
173
- const sendToWindows = (encoded) => {
174
- for (const window of BrowserWindow.getAllWindows()) window.webContents.send(EVENT_CHANNEL, encoded);
175
- };
176
- const binary = join(import.meta.dirname, "../../tools/resource-monitor/bin/resource-monitor");
177
- const startResourceMonitor = (userData) => {
178
- if (!existsSync(binary)) return;
179
- const instance = randomUUID();
180
- process.env["HINACODE_INSTANCE"] = instance;
181
- const log = join(userData, "resource-monitor", `${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-")}.ndjson`);
182
- spawn(binary, ["watch", "-root", String(process.pid), "-instance", instance, "-out", log], {
183
- detached: true,
184
- stdio: ["ignore", "ignore", "inherit"]
185
- }).on("error", (error) => console.error(`Resource monitor did not start: ${error.message}`)).unref();
186
- console.log(`Resource monitor log: ${log}`);
187
- };
188
- const require$1 = createRequire(import.meta.url);
189
- const liquidGlass = (() => {
190
- if (process.platform !== "darwin") return void 0;
191
- try {
192
- return require$1("electron-liquid-glass");
193
- } catch {
194
- return void 0;
195
- }
196
- })();
197
- const CHECK_INTERVAL = "4 hours";
198
- const make = gen(function* () {
199
- const current = app.getVersion();
200
- if (!app.isPackaged) return unsupported(current);
201
- const { autoUpdater } = updater;
202
- const events = yield* Events;
203
- let state = { type: "idle" };
204
- const set = (next) => {
205
- state = next;
206
- runFork(events.publish({ type: "update.changed" }));
207
- };
208
- autoUpdater.autoDownload = true;
209
- autoUpdater.on("checking-for-update", () => set({ type: "checking" }));
210
- autoUpdater.on("update-not-available", () => set({ type: "upToDate" }));
211
- autoUpdater.on("update-available", ({ version }) => set({ type: "downloading", version }));
212
- autoUpdater.on("update-downloaded", ({ version }) => set({ type: "ready", version }));
213
- autoUpdater.on("error", (error) => {
214
- set({ type: "failed", message: error.message });
215
- runFork(logWarning("update failed", error));
216
- });
217
- const check = suspend(
218
- () => state.type === "checking" || state.type === "downloading" || state.type === "ready" ? void_ : tryPromise(() => autoUpdater.checkForUpdates()).pipe(ignore)
219
- );
220
- yield* repeat(check, spaced(CHECK_INTERVAL)).pipe(forkScoped);
221
- return Updates.of({
222
- status: sync(() => ({ current, state })),
223
- check,
224
- install: sync(() => autoUpdater.quitAndInstall())
225
- });
226
- });
227
- const layer = effect(Updates, make);
228
- const devIcon = join$1(import.meta.dirname, "./chunks/icon-dev-DGWXI65o.png");
229
- const releaseIcon = join$1(import.meta.dirname, "./chunks/icon-B49l-pLu.png");
230
- app.setName("kkcode");
231
- if (process.platform === "win32") app.setAppUserModelId("app.hinacode");
232
- const userDataOverride = process.env["HINACODE_USER_DATA"];
233
- if (userDataOverride) app.setPath("userData", userDataOverride);
234
- if (!app.isPackaged) app.commandLine.appendSwitch("use-mock-keychain");
235
- if (!app.isPackaged && !userDataOverride) app.setPath("userData", join(app.getPath("appData"), "kkcode-dev"));
236
- if (!app.requestSingleInstanceLock()) {
237
- console.error(`HinaCode is already running on ${app.getPath("userData")}. Set HINACODE_USER_DATA to run another.`);
238
- app.exit(0);
239
- }
240
- if (!app.isPackaged) startResourceMonitor(app.getPath("userData"));
241
- const icon = app.isPackaged ? releaseIcon : devIcon;
242
- const pathHydrated = hydratePath(process.env);
243
- protocol.registerSchemesAsPrivileged([
244
- { scheme: ATTACHMENT_PROTOCOL, privileges: { standard: true, secure: true } },
245
- // `stream` lets <video> and <audio> seek with Range requests.
246
- { scheme: GITHUB_ASSET_PROTOCOL, privileges: { standard: true, secure: true, stream: true } },
247
- { scheme: PROJECT_FILE_PROTOCOL, privileges: { standard: true, secure: true, stream: true } }
248
- ]);
249
- const decodeCloudFile = decodeUnknownOption(RpcMethods["fs.preview"].response);
250
- const fetchFromCloud = async (runtime, environment, call) => {
251
- const envelope = await runtime.runPromise(
252
- flatMap(Environments, (environments) => environments.forward(environment, call))
253
- );
254
- const file = "error" in envelope ? void 0 : getOrUndefined(decodeCloudFile(envelope.result));
255
- return file === void 0 ? new Response(null, { status: 404 }) : fetch(file.dataUrl);
256
- };
257
- const sandboxed = (response) => {
258
- const headers = new Headers(response.headers);
259
- headers.set("content-security-policy", "sandbox allow-scripts");
260
- return new Response(response.body, { status: response.status, headers });
261
- };
262
- const serveAttachments = (runtime, attachmentsRoot) => protocol.handle(ATTACHMENT_PROTOCOL, async (request) => {
263
- const url = new URL(request.url);
264
- const path = decodeURIComponent(url.pathname.slice(1));
265
- const environment = url.searchParams.get("environment");
266
- if (environment !== null)
267
- return fetchFromCloud(runtime, environment, { method: "attachments.read", payload: { path } });
268
- if (!isInside(attachmentsRoot, path)) return new Response(null, { status: 403 });
269
- return net.fetch(pathToFileURL(path).toString());
270
- });
271
- const rangeOf = (request) => {
272
- const range = request.headers.get("range");
273
- return range === null ? {} : { headers: { range } };
274
- };
275
- const serveGitHubAssets = (runtime) => protocol.handle(GITHUB_ASSET_PROTOCOL, async (request) => {
276
- const id = githubAssetId(request.url);
277
- if (id === null) return new Response(null, { status: 404 });
278
- const token = await runtime.runPromise(flatMap(GitHub, (github) => github.token)).catch(() => null);
279
- if (token === null) return new Response(null, { status: 401 });
280
- const redirect = await fetch(`https://github.com/user-attachments/assets/${id}`, {
281
- headers: { authorization: `Bearer ${token}` },
282
- redirect: "manual"
283
- });
284
- const signed = externalUrl(redirect.headers.get("location") ?? "");
285
- if (signed === null) return new Response(null, { status: redirect.status === 404 ? 404 : 502 });
286
- return net.fetch(signed, rangeOf(request));
287
- });
288
- const serveProjectFiles = (runtime) => protocol.handle(PROJECT_FILE_PROTOCOL, async (request) => {
289
- const target = projectFileRequest(request.url);
290
- if (target === null) return new Response(null, { status: 404 });
291
- const cloud = await runtime.runPromise(
292
- map(Environments, (environments) => environments.owner("root", target.root))
293
- );
294
- if (cloud !== void 0)
295
- return sandboxed(await fetchFromCloud(runtime, cloud, { method: "fs.preview", payload: target }));
296
- const file = await runtime.runPromise(flatMap(Files, (files) => files.resolve(target.root, target.path))).catch(() => null);
297
- if (file === null) return new Response(null, { status: 403 });
298
- return sandboxed(await net.fetch(pathToFileURL(file).toString(), rangeOf(request)));
299
- });
300
- const safeStorageKeyring = succeed$1(
301
- Keyring,
302
- Keyring.of({
303
- seal: (value) => safeStorage.isEncryptionAvailable() ? safeStorage.encryptString(value) : void 0,
304
- open: (sealed) => safeStorage.decryptString(sealed)
305
- })
306
- );
307
- const QUIT_TIMEOUT_MS = 5e3;
308
- const devRendererUrl = app.isPackaged ? void 0 : process.env["ELECTRON_RENDERER_URL"];
309
- const appUrl = devRendererUrl ?? pathToFileURL(join(import.meta.dirname, "../renderer/index.html")).href;
310
- const httpOnly = (event) => {
311
- if (!externalUrl(event.url)) event.preventDefault();
312
- };
313
- const keepOnTheWeb = (page) => {
314
- page.setWindowOpenHandler(({ url }) => {
315
- const web = externalUrl(url);
316
- if (web) void page.loadURL(web);
317
- return { action: "deny" };
318
- });
319
- page.on("will-navigate", httpOnly);
320
- page.on("will-redirect", httpOnly);
321
- };
322
- const limitBrowserPermissions = () => {
323
- const browser = session.fromPartition(BROWSER_PARTITION);
324
- browser.setPermissionRequestHandler(
325
- (_page, permission, respond) => respond(permission === "clipboard-sanitized-write")
326
- );
327
- browser.setPermissionCheckHandler((_page, permission) => permission === "clipboard-sanitized-write");
328
- };
329
- const createWindow = () => {
330
- const window = new BrowserWindow({
331
- width: 1280,
332
- height: 820,
333
- minWidth: 720,
334
- minHeight: 480,
335
- show: false,
336
- // The glass draws behind the web contents, so the window itself must be clear.
337
- ...liquidGlass ? { transparent: true, backgroundColor: "#00000000" } : { backgroundColor: "#0a0a0a" },
338
- title: "HinaCode",
339
- icon,
340
- // The renderer draws its own title bar around the traffic lights (see TitleBar.tsx).
341
- ...process.platform === "darwin" && { titleBarStyle: "hidden", trafficLightPosition: { x: 14, y: 13 } },
342
- webPreferences: {
343
- preload: join(import.meta.dirname, "../preload/index.cjs"),
344
- sandbox: true,
345
- contextIsolation: true,
346
- webviewTag: true,
347
- additionalArguments: liquidGlass ? [LIQUID_GLASS_ARGUMENT] : []
348
- }
349
- });
350
- liquidGlass?.addView(window.getNativeWindowHandle());
351
- window.webContents.setWindowOpenHandler(({ url }) => {
352
- const external = externalUrl(url);
353
- if (external) void shell.openExternal(external);
354
- return { action: "deny" };
355
- });
356
- const stayInApp = (event) => {
357
- if (!isAllowedNavigation(event.url, event.isMainFrame, appUrl)) event.preventDefault();
358
- };
359
- window.webContents.on("will-frame-navigate", stayInApp);
360
- window.webContents.on("will-redirect", stayInApp);
361
- window.webContents.on("will-attach-webview", (event, preferences, params) => {
362
- if (!lockDownWebview(preferences, params)) event.preventDefault();
363
- });
364
- window.webContents.on("did-attach-webview", (_event, page) => keepOnTheWeb(page));
365
- void window.loadURL(appUrl);
366
- };
367
- const setMacMenu = () => Menu.setApplicationMenu(
368
- Menu.buildFromTemplate([
369
- {
370
- label: "HinaCode",
371
- submenu: [
372
- { role: "about", label: "About HinaCode" },
373
- { type: "separator" },
374
- { role: "services" },
375
- { type: "separator" },
376
- { role: "hide", label: "Hide HinaCode" },
377
- { role: "hideOthers" },
378
- { role: "unhide" },
379
- { type: "separator" },
380
- { role: "quit", label: "Quit HinaCode" }
381
- ]
382
- },
383
- { role: "fileMenu" },
384
- { role: "editMenu" },
385
- { role: "viewMenu" },
386
- { role: "windowMenu" }
387
- ])
388
- );
389
- app.whenReady().then(async () => {
390
- await pathHydrated;
391
- const userData = app.getPath("userData");
392
- const sbxConfigPath = join(app.getPath("appData"), "sbx", "config.json");
393
- const dbPath = join(userData, "hinacode.sqlite");
394
- if (!existsSync(dbPath)) {
395
- for (const suffix of ["", "-wal", "-shm"]) {
396
- const previous = join(userData, `kkcode.sqlite${suffix}`);
397
- if (existsSync(previous)) renameSync(previous, `${dbPath}${suffix}`);
398
- }
399
- }
400
- const runtime = make$1(
401
- makeAppLayer({
402
- userData,
403
- sbxConfigPath,
404
- keyring: safeStorageKeyring,
405
- updates: layer,
406
- toWindows: sendToWindows
407
- })
408
- );
409
- await runtime.runPromise(void_);
410
- let disposed = false;
411
- app.on("before-quit", (event) => {
412
- if (disposed) return;
413
- event.preventDefault();
414
- disposed = true;
415
- const disposal = runtime.dispose().catch((cause) => console.error("runtime dispose failed", cause));
416
- const timeout = new Promise((resolve) => setTimeout(resolve, QUIT_TIMEOUT_MS));
417
- void Promise.race([disposal, timeout]).then(() => app.quit());
418
- });
419
- registerIpc(runtime, appUrl);
420
- powerMonitor.on(
421
- "resume",
422
- () => runtime.runFork(flatMap(Environments, (environments) => environments.reconnectAll))
423
- );
424
- app.dock?.setIcon(icon);
425
- if (process.platform === "darwin") setMacMenu();
426
- serveAttachments(runtime, join(userData, "attachments"));
427
- serveGitHubAssets(runtime);
428
- serveProjectFiles(runtime);
429
- limitBrowserPermissions();
430
- app.on("activate", () => {
431
- if (BrowserWindow.getAllWindows().length === 0) createWindow();
432
- });
433
- app.on("second-instance", () => {
434
- const [window] = BrowserWindow.getAllWindows();
435
- if (window) bringToFront(window);
436
- else createWindow();
437
- });
438
- createWindow();
439
- });
440
- app.on("window-all-closed", () => {
441
- if (process.platform !== "darwin") app.quit();
442
- });