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.
@@ -1,286 +0,0 @@
1
- import { mkdirSync, existsSync, readlinkSync, writeFileSync, readFileSync, rmSync } from "node:fs";
2
- import { createRequire } from "node:module";
3
- import { homedir, hostname } from "node:os";
4
- import { dirname, delimiter, basename, join } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import QRCode from "qrcode";
7
- import { S as Struct, e as effect, U as Updates, g as gen, u as unsupported, E as Events, t as tryPromise, d as decodeUnknownSync, m as make$1, s as suspend, r as repeat, a as spaced, f as forkScoped, T as Threads, W as Worktrees, b as Terminals, c as forEach, o as orElseSucceed, h as sync, i as isThreadBusy, j as String$1, v as void_, k as andThen, l as matchEffect, n as forkDetach, p as flatMap, q as UsageError, w as USAGE, x as parseCommand, y as serveConfig, z as hydratePath, A as make$2, B as makeAppLayer, C as autoUpdate, D as applyServeRelay, R as RemoteAccess, F as layer$1, G as provideMerge, H as mergeAll, I as layer$2, J as layer$3, K as noKeyring, L as layer$4, M as provide, N as succeed, O as MinimumLogLevel, P as Settings, Q as storedTunnel, V as isPortInUse, X as pairingUrl, Y as restartCommand } from "./chunks/shellPath-B4T8uBcy.js";
8
- import { execFile } from "node:child_process";
9
- import { promisify } from "node:util";
10
- import "node:crypto";
11
- import "node:stream";
12
- import "node:readline";
13
- import "node:fs/promises";
14
- import "@anthropic-ai/claude-agent-sdk";
15
- import "@modelcontextprotocol/sdk/client/streamableHttp.js";
16
- import "@modelcontextprotocol/sdk/types.js";
17
- import "@muse-code/sdk";
18
- import "node:sqlite";
19
- import "node-pty";
20
- import "playwright";
21
- import "ws";
22
- import "@noble/hashes/hmac.js";
23
- import "@noble/hashes/sha2.js";
24
- import "@noble/hashes/utils.js";
25
- import "node:http";
26
- import "node:stream/promises";
27
- import "node:zlib";
28
- import "node:net";
29
- import "node:tls";
30
- const execFileAsync = promisify(execFile);
31
- const CHECK_INTERVAL = "4 hours";
32
- const AUTO_INSTALL_INTERVAL = "1 minute";
33
- const INSTALL_TIMEOUT_MS = 10 * 6e4;
34
- const NpmRelease = Struct({ version: String$1 });
35
- const globalPrefix = (packageRoot2) => {
36
- const nodeModules = dirname(packageRoot2);
37
- const lib = dirname(nodeModules);
38
- const isGlobal = basename(packageRoot2) === "hinacode" && basename(nodeModules) === "node_modules";
39
- return isGlobal && basename(lib) === "lib" ? dirname(lib) : void 0;
40
- };
41
- const isIdle = (cloud) => cloud.terminals.every((terminal) => terminal.status !== "running") && cloud.threads.every((thread) => !isThreadBusy(thread.status) && thread.queue.length === 0) && cloud.worktrees.every((worktree) => worktree.status !== "preparing");
42
- const make = ({ current, packageRoot: packageRoot2, registry, restart, autoInstall }) => gen(function* () {
43
- const prefix = globalPrefix(packageRoot2);
44
- if (prefix === void 0 || process.platform === "win32") return unsupported(current);
45
- const events = yield* Events;
46
- let state = { type: "idle" };
47
- const set = (next) => suspend(() => {
48
- state = next;
49
- return events.publish({ type: "update.changed" });
50
- });
51
- const latest = tryPromise(async () => {
52
- const response = await fetch(`${registry.replace(/\/$/, "")}/hinacode/latest`, {
53
- signal: AbortSignal.timeout(1e4)
54
- });
55
- if (!response.ok) throw new Error(`npm answered ${response.status}`);
56
- return decodeUnknownSync(NpmRelease)(await response.json()).version;
57
- });
58
- const checkLock = yield* make$1(1);
59
- const check = suspend(
60
- () => state.type === "downloading" ? void_ : set({ type: "checking" }).pipe(
61
- andThen(latest),
62
- matchEffect({
63
- onFailure: (error) => set({ type: "failed", message: `Could not check for updates: ${error.message}` }),
64
- onSuccess: (version2) => set(version2 === current ? { type: "upToDate" } : { type: "ready", version: version2 })
65
- })
66
- )
67
- ).pipe(checkLock.withPermit);
68
- const npmEnv = { ...process.env, PATH: [dirname(process.execPath), process.env["PATH"]].join(delimiter) };
69
- const npmInstall = (version2) => tryPromise({
70
- try: () => execFileAsync(
71
- "npm",
72
- [
73
- "install",
74
- "--global",
75
- `--prefix=${prefix}`,
76
- `--registry=${registry}`,
77
- // npm 11 skips install scripts it was not told to run, and node-pty's picks its prebuilt binary.
78
- "--allow-scripts=node-pty",
79
- `hinacode@${version2}`
80
- ],
81
- { env: npmEnv, encoding: "utf8", timeout: INSTALL_TIMEOUT_MS }
82
- ),
83
- catch: (cause) => new Error(cause.stderr?.trim().split("\n").slice(-3).join("\n") || String(cause))
84
- });
85
- const install = suspend(() => {
86
- if (state.type !== "ready") return void_;
87
- const { version: version2 } = state;
88
- return set({ type: "downloading", version: version2 }).pipe(
89
- andThen(
90
- npmInstall(version2).pipe(
91
- matchEffect({
92
- onFailure: (error) => set({ type: "failed", message: error.message }),
93
- onSuccess: () => sync(restart)
94
- }),
95
- // The caller's rpc returns now; the cloud restarts once npm finishes.
96
- forkDetach
97
- )
98
- )
99
- );
100
- });
101
- yield* repeat(check, spaced(CHECK_INTERVAL)).pipe(forkScoped);
102
- const [threads, worktrees, terminals] = [yield* Threads, yield* Worktrees, yield* Terminals];
103
- const idle = gen(function* () {
104
- const list = yield* threads.list;
105
- const sessions = yield* forEach(list, (thread) => terminals.list(thread.id));
106
- return isIdle({ threads: list, worktrees: yield* worktrees.list, terminals: sessions.flat() });
107
- }).pipe(orElseSucceed(() => false));
108
- const installWhenIdle = suspend(
109
- () => state.type === "ready" ? flatMap(idle, (yes) => yes ? install : void_) : void_
110
- );
111
- if (autoInstall)
112
- yield* repeat(installWhenIdle, spaced(AUTO_INSTALL_INTERVAL)).pipe(forkScoped);
113
- return Updates.of({
114
- status: sync(() => ({ current, state })),
115
- check,
116
- install
117
- });
118
- });
119
- const layer = (options) => effect(Updates, make(options));
120
- const QUIT_TIMEOUT_MS = 5e3;
121
- const LISTEN_TIMEOUT_MS = 5e3;
122
- const { version } = createRequire(import.meta.url)("../../package.json");
123
- const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
124
- const appData = () => process.platform === "darwin" ? join(homedir(), "Library", "Application Support") : process.platform === "win32" ? process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming") : process.env["XDG_CONFIG_HOME"] ?? join(homedir(), ".config");
125
- const isAlive = (pid) => {
126
- try {
127
- process.kill(pid, 0);
128
- return true;
129
- } catch (error) {
130
- return error.code === "EPERM";
131
- }
132
- };
133
- const lockDataDir = (dir) => {
134
- const desktop = (() => {
135
- try {
136
- return readlinkSync(join(dir, "SingletonLock"));
137
- } catch {
138
- return void 0;
139
- }
140
- })();
141
- const desktopPid = desktop?.startsWith(`${hostname()}-`) ? Number(desktop.slice(hostname().length + 1)) : NaN;
142
- if (isAlive(desktopPid)) throw new Error(`the HinaCode app (pid ${desktopPid}) uses ${dir}`);
143
- const path = join(dir, "daemon.pid");
144
- for (; ; ) {
145
- try {
146
- writeFileSync(path, String(process.pid), { flag: "wx" });
147
- break;
148
- } catch (error) {
149
- if (error.code !== "EEXIST") throw error;
150
- const pid = Number(readFileSync(path, "utf8"));
151
- if (pid === process.pid) break;
152
- if (isAlive(pid)) throw new Error(`another hinacode serve (pid ${pid}) uses ${dir}`, { cause: error });
153
- rmSync(path, { force: true });
154
- }
155
- }
156
- process.on("exit", () => rmSync(path, { force: true }));
157
- };
158
- const pairingText = async (userData, pairing) => {
159
- const phoneUrl = pairingUrl(pairing);
160
- const qr = await QRCode.toString(phoneUrl, { type: "terminal", small: true });
161
- return [
162
- `HinaCode cloud ${version}`,
163
- `data: ${userData}`,
164
- "",
165
- "Pair a phone: scan this code in the HinaCode app, or paste the URL.",
166
- ` ${phoneUrl}`,
167
- qr,
168
- ...pairing.relay === null ? [] : [`Reachable from any network through ${pairing.relay}.`, ""],
169
- "Pair a desktop: Settings > Environments > Add environment, with one of:",
170
- ...pairing.hosts.map((host) => ` ${pairingUrl({ ...pairing, hosts: [host] })}`),
171
- "Keep the token in these URLs private. Run `hinacode pair` to print them again.",
172
- ""
173
- ].join("\n");
174
- };
175
- const printLink = ({ url, userCode }) => sync(
176
- () => process.stdout.write(`Open ${url} to link this cloud to your HinaCode account. The code is ${userCode}.
177
- `)
178
- );
179
- const listening = async (runtime) => {
180
- const deadline = Date.now() + LISTEN_TIMEOUT_MS;
181
- for (; ; ) {
182
- const status = await runtime.runPromise(RemoteAccess.use((remote) => remote.status));
183
- if (status.listening) break;
184
- if (status.listenError !== null && isPortInUse(status.listenError)) {
185
- const { port } = (await runtime.runPromise(Settings.use((settings) => settings.get))).remote;
186
- throw new Error(
187
- `port ${port} is in use, perhaps by the HinaCode desktop's Remote or another cloud. Pick another with --port <n>.`
188
- );
189
- }
190
- if (status.listenError !== null) throw new Error(`remote listener failed: ${status.listenError}`);
191
- if (Date.now() > deadline) throw new Error("remote listener did not start in time");
192
- await new Promise((resolve) => setTimeout(resolve, 50));
193
- }
194
- };
195
- const serve = async (argv, userData) => {
196
- const config = serveConfig(argv, process.env);
197
- mkdirSync(userData, { recursive: true, mode: 448 });
198
- lockDataDir(userData);
199
- await hydratePath(process.env);
200
- const runtime = make$2(
201
- makeAppLayer({
202
- userData,
203
- sbxConfigPath: join(appData(), "sbx", "config.json"),
204
- keyring: noKeyring,
205
- updates: layer({
206
- current: version,
207
- packageRoot,
208
- registry: process.env["npm_config_registry"] || "https://registry.npmjs.org",
209
- autoInstall: autoUpdate(process.env),
210
- restart: () => stop(() => {
211
- const { file, args, env } = restartCommand(process);
212
- process.execve(file, args, env);
213
- })
214
- }),
215
- toWindows: () => {
216
- },
217
- serve: config
218
- })
219
- );
220
- let stopping = false;
221
- const stop = (then) => {
222
- if (stopping) return;
223
- stopping = true;
224
- const disposal = runtime.dispose().catch((cause) => console.error("runtime dispose failed", cause));
225
- const timeout = new Promise((resolve) => setTimeout(resolve, QUIT_TIMEOUT_MS));
226
- void Promise.race([disposal, timeout]).then(then);
227
- };
228
- const quit = () => stop(() => process.exit(0));
229
- process.on("SIGINT", quit);
230
- process.on("SIGTERM", quit);
231
- await runtime.runPromise(void_);
232
- await listening(runtime);
233
- try {
234
- await runtime.runPromise(applyServeRelay(config.relay, printLink));
235
- } catch (error) {
236
- await runtime.dispose();
237
- throw error;
238
- }
239
- const pairing = await runtime.runPromise(RemoteAccess.use((remote) => remote.pairing));
240
- process.stdout.write(await pairingText(userData, pairing));
241
- };
242
- const pair = async (userData) => {
243
- const database = join(userData, "hinacode.sqlite");
244
- const noCloud = () => {
245
- process.stderr.write(`No cloud in ${userData} yet. Start one with \`hinacode serve\`.
246
- `);
247
- process.exitCode = 1;
248
- };
249
- if (!existsSync(database)) return noCloud();
250
- const runtime = make$2(
251
- layer$1.pipe(
252
- provideMerge(mergeAll(layer$3, layer$2)),
253
- provideMerge(mergeAll(layer$4(database), noKeyring)),
254
- provide(succeed(MinimumLogLevel, "Warn"))
255
- )
256
- );
257
- try {
258
- const { remote } = await runtime.runPromise(Settings.use((settings) => settings.get));
259
- if (!remote.enabled) return noCloud();
260
- const pairing = await runtime.runPromise(RemoteAccess.use((access) => access.pairing));
261
- const tunnel = await runtime.runPromise(storedTunnel);
262
- process.stdout.write(await pairingText(userData, { ...pairing, relay: tunnel?.hostname ?? null }));
263
- } finally {
264
- await runtime.dispose();
265
- }
266
- };
267
- const main = async (argv) => {
268
- const command = parseCommand(argv);
269
- if (command === "help") return void process.stdout.write(`${USAGE}
270
- `);
271
- if (command === "version") return void process.stdout.write(`${version}
272
- `);
273
- const userData = process.env["HINACODE_USER_DATA"] || join(homedir(), ".hinacode-cloud");
274
- return command === "serve" ? serve(argv, userData) : pair(userData);
275
- };
276
- main(process.argv.slice(2)).catch((error) => {
277
- if (error instanceof UsageError) {
278
- process.stderr.write(`hinacode: ${error.message}
279
-
280
- ${USAGE}
281
- `);
282
- } else {
283
- console.error(`hinacode ${process.argv[2]}: ${error instanceof Error ? error.message : String(error)}`);
284
- }
285
- process.exit(1);
286
- });