hypeframe 0.3.0 → 0.5.1
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/README.md +66 -8
- package/dist/index.js +1777 -313
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/cli/args.ts
|
|
2
2
|
var VALUE = new Map([
|
|
3
3
|
["--gateway", "gateway"],
|
|
4
4
|
["--web", "web"],
|
|
@@ -14,7 +14,8 @@ var SWITCH = new Map([
|
|
|
14
14
|
["--help", "help"],
|
|
15
15
|
["-h", "help"],
|
|
16
16
|
["--version", "version"],
|
|
17
|
-
["-v", "version"]
|
|
17
|
+
["-v", "version"],
|
|
18
|
+
["--download", "download"]
|
|
18
19
|
]);
|
|
19
20
|
var ALIAS = { keluar: "logout", masuk: "login", mulai: "start", bantuan: "help" };
|
|
20
21
|
function parseArgs(argv) {
|
|
@@ -48,10 +49,10 @@ function parseArgs(argv) {
|
|
|
48
49
|
return out;
|
|
49
50
|
}
|
|
50
51
|
|
|
51
|
-
//
|
|
52
|
+
// src/config/account.ts
|
|
52
53
|
import fs2 from "node:fs";
|
|
53
54
|
|
|
54
|
-
//
|
|
55
|
+
// src/config/paths.ts
|
|
55
56
|
import fs from "node:fs";
|
|
56
57
|
import os from "node:os";
|
|
57
58
|
import path from "node:path";
|
|
@@ -71,8 +72,14 @@ var lockFile = () => path.join(dataDir(), "mesin.kunci");
|
|
|
71
72
|
var logDir = () => sub("log");
|
|
72
73
|
var cacheDir = () => sub("cache");
|
|
73
74
|
var renderDir = () => sub("kerja", "render");
|
|
75
|
+
var agentDir = () => sub("agen");
|
|
76
|
+
function projectDir(projectId) {
|
|
77
|
+
if (!/^[A-Za-z0-9_-]{1,80}$/.test(projectId))
|
|
78
|
+
throw new Error("invalid project id");
|
|
79
|
+
return sub("proyek", projectId);
|
|
80
|
+
}
|
|
74
81
|
|
|
75
|
-
//
|
|
82
|
+
// src/config/account.ts
|
|
76
83
|
function readAccount() {
|
|
77
84
|
try {
|
|
78
85
|
const a = JSON.parse(fs2.readFileSync(accountFile(), "utf8"));
|
|
@@ -94,7 +101,7 @@ function maskEmail(email) {
|
|
|
94
101
|
return m ? `${m[1]}***${m[2]}`.replace(/[\u0000-\u001f\u007f]/g, "") : "-";
|
|
95
102
|
}
|
|
96
103
|
|
|
97
|
-
//
|
|
104
|
+
// src/config/settings.ts
|
|
98
105
|
import fs3 from "node:fs";
|
|
99
106
|
import os2 from "node:os";
|
|
100
107
|
var DEFAULT_GATEWAY = "https://api.sairipedia.com";
|
|
@@ -125,7 +132,7 @@ function osName() {
|
|
|
125
132
|
return { win32: "windows", darwin: "macos", linux: "linux", android: "android" }[process.platform] || process.platform;
|
|
126
133
|
}
|
|
127
134
|
|
|
128
|
-
//
|
|
135
|
+
// src/ui/locale.ts
|
|
129
136
|
function systemLang() {
|
|
130
137
|
const env = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale || "";
|
|
131
138
|
return /^id\b|^id[-_]|^in[-_]/i.test(env) ? "id" : "en";
|
|
@@ -193,6 +200,32 @@ var id = {
|
|
|
193
200
|
"menu.exit": "Keluar",
|
|
194
201
|
"menu.bye": "Sampai jumpa.",
|
|
195
202
|
"agent.soon": "Asisten AI yang bekerja langsung di perangkatmu sedang disiapkan.",
|
|
203
|
+
"agent.menuQuestion": "Pilih agen. Pasang dan masuk akun sekali di sini, lalu mengobrol dari HypeFrame Web.",
|
|
204
|
+
"agent.ready": "siap dipakai dari web",
|
|
205
|
+
"agent.needLogin": "perlu masuk akun",
|
|
206
|
+
"agent.notInstalled": "belum dipasang",
|
|
207
|
+
"agent.add": "Pasang dan masuk akun",
|
|
208
|
+
"agent.login": "Masuk akun lagi",
|
|
209
|
+
"agent.remove": "Lepas dari mesin ini",
|
|
210
|
+
"agent.back": "Kembali",
|
|
211
|
+
"agent.installing": "Memasang {name} dari daftar resmi ACP...",
|
|
212
|
+
"agent.installed": "{name} {version} terpasang.",
|
|
213
|
+
"agent.loggingIn": "Masuk akun {name}...",
|
|
214
|
+
"agent.loggedIn": "{name} siap. Buka HypeFrame Web lalu pilih {name} di Asisten (mesin harus menyala).",
|
|
215
|
+
"agent.loginFailed": "{name} belum bisa dipakai: masuk akun belum berhasil. Coba lagi dari menu Asisten AI.",
|
|
216
|
+
"agent.askKey": "Tempel {name}",
|
|
217
|
+
"agent.removed": "{name} dilepas dari mesin ini.",
|
|
218
|
+
"agent.unknown": "Agen {id} tidak didukung. Pilihan: {list}",
|
|
219
|
+
"agent.notInstalledYet": "{name} belum dipasang. Jalankan: hypeframe agent add",
|
|
220
|
+
"agent.webHint": "Mengobrol dengan agen dilakukan di HypeFrame Web, halaman Asisten, selama mesin menyala.",
|
|
221
|
+
"agent.toolNoTab": "Agen memanggil alat HypeFrame, tapi tab HypeFrame Web tidak terbuka. Buka HypeFrame Web lalu kirim pesannya lagi.",
|
|
222
|
+
"agent.toolNoAnswer": "Agen memanggil alat HypeFrame, tapi HypeFrame Web tidak menjawab. Pastikan tabnya terbuka.",
|
|
223
|
+
"agent.keyFromShellAsk": "Pakai {name} yang sudah ada di terminal ini?",
|
|
224
|
+
"agent.keyFromShell": "Memakai {name} dari terminal ini (disimpan untuk agen ini saja).",
|
|
225
|
+
"agent.own": "{name} sudah terpasang di komputer ini ({path}); yang itu dipakai, tidak diunduh lagi.",
|
|
226
|
+
"agent.ownFailed": "Kalau {name} milikmu terlalu lama, pasang versi resmi: hypeframe agent add {id} --download",
|
|
227
|
+
"agent.ownTag": "punyamu sendiri",
|
|
228
|
+
"menu.agentReady": "{n} agen siap",
|
|
196
229
|
"status.account": "Akun",
|
|
197
230
|
"status.engine": "Mesin",
|
|
198
231
|
"status.device": "Perangkat",
|
|
@@ -268,6 +301,7 @@ var id = {
|
|
|
268
301
|
"help.open": "buka HypeFrame Web di browser",
|
|
269
302
|
"help.doctor": "periksa Node, Chrome, ffmpeg, koneksi, ruang disk",
|
|
270
303
|
"help.bench": "ukur kecepatan render 720p dan 1080p",
|
|
304
|
+
"help.agent": "pasang dan masuk akun agen AI dengan langgananmu sendiri (Antigravity, Codex, OpenCode)",
|
|
271
305
|
"help.history": "render 24 jam terakhir",
|
|
272
306
|
"help.autostart": "nyalakan mesin saat masuk ke komputer",
|
|
273
307
|
"help.config": "nama perangkat, GPU, bahasa",
|
|
@@ -333,6 +367,32 @@ var en = {
|
|
|
333
367
|
"menu.exit": "Exit",
|
|
334
368
|
"menu.bye": "See you.",
|
|
335
369
|
"agent.soon": "An AI assistant that works right on your device is on the way.",
|
|
370
|
+
"agent.menuQuestion": "Pick an agent. Install and log in once here, then chat from HypeFrame Web.",
|
|
371
|
+
"agent.ready": "ready to use from the web",
|
|
372
|
+
"agent.needLogin": "needs login",
|
|
373
|
+
"agent.notInstalled": "not installed",
|
|
374
|
+
"agent.add": "Install and log in",
|
|
375
|
+
"agent.login": "Log in again",
|
|
376
|
+
"agent.remove": "Remove from this machine",
|
|
377
|
+
"agent.back": "Back",
|
|
378
|
+
"agent.installing": "Installing {name} from the official ACP registry...",
|
|
379
|
+
"agent.installed": "{name} {version} installed.",
|
|
380
|
+
"agent.loggingIn": "Logging in to {name}...",
|
|
381
|
+
"agent.loggedIn": "{name} is ready. Open HypeFrame Web and pick {name} in the Assistant (the engine must be running).",
|
|
382
|
+
"agent.loginFailed": "{name} is not usable yet: the login did not succeed. Try again from the AI assistant menu.",
|
|
383
|
+
"agent.askKey": "Paste {name}",
|
|
384
|
+
"agent.removed": "{name} removed from this machine.",
|
|
385
|
+
"agent.unknown": "Agent {id} is not supported. Choices: {list}",
|
|
386
|
+
"agent.notInstalledYet": "{name} is not installed. Run: hypeframe agent add",
|
|
387
|
+
"agent.webHint": "Chatting with agents happens in HypeFrame Web, on the Assistant page, while the engine runs.",
|
|
388
|
+
"agent.toolNoTab": "An agent called a HypeFrame tool, but no HypeFrame Web tab is open. Open HypeFrame Web and send the message again.",
|
|
389
|
+
"agent.toolNoAnswer": "An agent called a HypeFrame tool, but HypeFrame Web did not answer. Make sure its tab is open.",
|
|
390
|
+
"agent.keyFromShellAsk": "Use the {name} already set in this terminal?",
|
|
391
|
+
"agent.keyFromShell": "Using {name} from this terminal (saved for this agent only).",
|
|
392
|
+
"agent.own": "{name} is already installed on this computer ({path}); that copy is used, nothing is downloaded.",
|
|
393
|
+
"agent.ownFailed": "If your own {name} is too old, install the official one: hypeframe agent add {id} --download",
|
|
394
|
+
"agent.ownTag": "your own copy",
|
|
395
|
+
"menu.agentReady": "{n} agents ready",
|
|
336
396
|
"status.account": "Account",
|
|
337
397
|
"status.engine": "Engine",
|
|
338
398
|
"status.device": "Device",
|
|
@@ -408,6 +468,7 @@ var en = {
|
|
|
408
468
|
"help.open": "open HypeFrame Web in the browser",
|
|
409
469
|
"help.doctor": "check Node, Chrome, ffmpeg, network, disk space",
|
|
410
470
|
"help.bench": "measure render speed at 720p and 1080p",
|
|
471
|
+
"help.agent": "install and log in AI agents with your own subscription (Antigravity, Codex, OpenCode)",
|
|
411
472
|
"help.history": "renders from the last 24 hours",
|
|
412
473
|
"help.autostart": "start the engine when you sign in",
|
|
413
474
|
"help.config": "device name, GPU, language",
|
|
@@ -425,11 +486,11 @@ function t(key, vars = {}) {
|
|
|
425
486
|
return s.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? `{${k}}`));
|
|
426
487
|
}
|
|
427
488
|
|
|
428
|
-
//
|
|
489
|
+
// src/ui/log.ts
|
|
429
490
|
import fs4 from "node:fs";
|
|
430
491
|
import path2 from "node:path";
|
|
431
492
|
|
|
432
|
-
//
|
|
493
|
+
// src/ui/theme.ts
|
|
433
494
|
import picocolors from "picocolors";
|
|
434
495
|
var env = process.env;
|
|
435
496
|
var enabled = !("NO_COLOR" in env) && env.TERM !== "dumb" && ("FORCE_COLOR" in env ? env.FORCE_COLOR !== "0" : !!process.stdout.isTTY);
|
|
@@ -463,7 +524,7 @@ var icon = {
|
|
|
463
524
|
};
|
|
464
525
|
var plain = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
465
526
|
|
|
466
|
-
//
|
|
527
|
+
// src/ui/log.ts
|
|
467
528
|
var SECRET = /\b(hfm_[A-Za-z0-9_-]{20,}|hms_[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|v1\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,})\b/g;
|
|
468
529
|
var mask = (s) => s.replace(SECRET, (m) => `${m.slice(0, 4)}…`);
|
|
469
530
|
var MAX_FILE = 1024 * 1024;
|
|
@@ -501,12 +562,12 @@ var log = {
|
|
|
501
562
|
detail: (m) => write("detail", m)
|
|
502
563
|
};
|
|
503
564
|
|
|
504
|
-
//
|
|
505
|
-
import
|
|
565
|
+
// src/cli/commands/start.ts
|
|
566
|
+
import crypto7 from "node:crypto";
|
|
506
567
|
|
|
507
|
-
//
|
|
568
|
+
// ../protocol/src/index.ts
|
|
508
569
|
var PROTOCOL_VERSION = 1;
|
|
509
|
-
var ALLOWED_KINDS = ["status", "kunci"];
|
|
570
|
+
var ALLOWED_KINDS = ["status", "kunci", "agen.mulai", "agen.kirim", "agen.izin", "agen.batal", "agen.opsi", "agen.riwayat"];
|
|
510
571
|
var CloseCode = {
|
|
511
572
|
BadHello: 4001,
|
|
512
573
|
Replaced: 4002,
|
|
@@ -527,59 +588,15 @@ var EngineError = {
|
|
|
527
588
|
BadPackage: "Paket berisi berkas yang tidak diizinkan."
|
|
528
589
|
};
|
|
529
590
|
|
|
530
|
-
//
|
|
531
|
-
import
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
var alive = (pid) => {
|
|
536
|
-
try {
|
|
537
|
-
process.kill(pid, 0);
|
|
538
|
-
return true;
|
|
539
|
-
} catch (e) {
|
|
540
|
-
return e.code === "EPERM";
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
function runningPid() {
|
|
544
|
-
try {
|
|
545
|
-
const pid = Number(fs5.readFileSync(lockFile(), "utf8"));
|
|
546
|
-
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
|
|
547
|
-
} catch {
|
|
548
|
-
return null;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
function singleInstance() {
|
|
552
|
-
const f = lockFile();
|
|
553
|
-
for (let attempt = 0;attempt < 2; attempt++) {
|
|
554
|
-
try {
|
|
555
|
-
const fd = fs5.openSync(f, "wx");
|
|
556
|
-
fs5.writeSync(fd, String(process.pid));
|
|
557
|
-
fs5.closeSync(fd);
|
|
558
|
-
const release = () => {
|
|
559
|
-
try {
|
|
560
|
-
if (fs5.readFileSync(f, "utf8") === String(process.pid))
|
|
561
|
-
fs5.rmSync(f, { force: true });
|
|
562
|
-
} catch {}
|
|
563
|
-
process.off("exit", release);
|
|
564
|
-
};
|
|
565
|
-
process.on("exit", release);
|
|
566
|
-
return { release };
|
|
567
|
-
} catch (e) {
|
|
568
|
-
if (e.code !== "EEXIST")
|
|
569
|
-
throw e;
|
|
570
|
-
const pid = Number(fs5.readFileSync(f, "utf8"));
|
|
571
|
-
if (Number.isInteger(pid) && pid > 0 && alive(pid))
|
|
572
|
-
throw new AlreadyRunning("engine already running");
|
|
573
|
-
fs5.rmSync(f, { force: true });
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
throw new AlreadyRunning("engine already running");
|
|
577
|
-
}
|
|
578
|
-
// packages/hypeframe/package.json
|
|
591
|
+
// src/agent/service.ts
|
|
592
|
+
import crypto2 from "node:crypto";
|
|
593
|
+
import fs8 from "node:fs";
|
|
594
|
+
import path5 from "node:path";
|
|
595
|
+
// package.json
|
|
579
596
|
var package_default = {
|
|
580
597
|
name: "hypeframe",
|
|
581
|
-
version: "0.
|
|
582
|
-
description: "Local engine for HypeFrame Web: code clips, video renders and
|
|
598
|
+
version: "0.5.1",
|
|
599
|
+
description: "Local engine for HypeFrame Web: code clips, video renders and AI agents run on your own machine; the web is just the view.",
|
|
583
600
|
keywords: [
|
|
584
601
|
"hypeframe",
|
|
585
602
|
"video",
|
|
@@ -628,15 +645,1047 @@ var package_default = {
|
|
|
628
645
|
}
|
|
629
646
|
};
|
|
630
647
|
|
|
631
|
-
//
|
|
648
|
+
// src/config/version.ts
|
|
632
649
|
var VERSION = process.env.HF_MESIN_VERSI || package_default.version;
|
|
633
650
|
|
|
634
|
-
//
|
|
651
|
+
// src/agent/instructions.ts
|
|
652
|
+
var MCP_INSTRUCTIONS = "Tools to make videos from code in HypeFrame Web, open in the user's browser. Tools run in that browser tab, so HypeFrame Web must stay open. " + "A project is a sequence of scenes written in code (create_motion with engine halaman, html, gsap or remotion) plus sound written in code (create_audio, Web Audio). " + "CODE FIRST (the main feature of HypeFrame): build every scene of a new video by writing code and passing it in the code argument of preview_motion and then create_motion (engine halaman, html, gsap or remotion), and make sound with create_audio. Writing that code through these tools is your main job here; never say you cannot write code. Do not build scenes from add_text, add_shape or add_image layers: use those (and set_keyframe) only when the user asks for a small manual change to a video that already exists. " + "Try code with preview_motion first. Depending on the permission setting of the user, create_motion / create_audio runs at once (the code is still shown in HypeFrame Web) or waits until the user approves it, so wait for the job result with get_job_status. " + "At the start of every conversation call get_memory first: it shows unfinished work saved by earlier conversations. If there is unfinished work, say in one or two sentences what it was and ask whether to continue it. " + "Keep the memory current: call save_memory after every finished step. " + "Before creating a project, call list_skills, pick the best skill (say which) and read it with use_skill. A skill can be a package with files: read examples with read_skill_file and put assets into the project with import_skill_files. " + "All times are in frames (seconds x project fps). " + "render_video may ask the user to approve (their setting) and returns immediately: poll get_render_status until it finishes. Most users write in Indonesian: write every message, including progress notes, in their language.";
|
|
653
|
+
var AGENTS_MD = `# HypeFrame
|
|
654
|
+
|
|
655
|
+
You are running on the user's computer through the HypeFrame engine. The user types to you from HypeFrame Web (in a browser, possibly on another device) to make videos. This folder is the only place you may read or write files.
|
|
656
|
+
|
|
657
|
+
- Make and edit the video only with the tools of the MCP server "hypeframe". The project lives in HypeFrame Web, not in this folder: do not write files or run shell commands for it. Write the scene code directly in the code argument of preview_motion / create_motion (that is how HypeFrame videos are made: from code).
|
|
658
|
+
- ${MCP_INSTRUCTIONS}
|
|
659
|
+
- The user is usually not a programmer. Reply in their language (most write Indonesian), short and plain, without technical words.
|
|
660
|
+
- When create_motion or create_audio waits for approval (the tool result says so), tell the user to check the editor in HypeFrame Web.
|
|
661
|
+
- A file you made or downloaded in this folder (image, audio, video, font, Lottie/JSON, up to 4 MB) reaches the video only through add_file_from_computer, which returns its asset id (use it as asset://<id>).
|
|
662
|
+
`;
|
|
663
|
+
|
|
664
|
+
// src/agent/registry.ts
|
|
665
|
+
import { spawnSync } from "node:child_process";
|
|
666
|
+
import fs5 from "node:fs";
|
|
667
|
+
var SUPPORTED_AGENTS = ["antigravity-acp", "codex-acp", "opencode"];
|
|
668
|
+
var isSupported = (id) => SUPPORTED_AGENTS.includes(id);
|
|
669
|
+
var OFFICIAL_REGISTRY = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
|
670
|
+
var registryUrl = () => process.env.HYPEFRAME_ACP_REGISTRY || OFFICIAL_REGISTRY;
|
|
671
|
+
var isLocalRegistry = (u) => u.startsWith("file:") || /^http:\/\/127\.0\.0\.1[:/]/.test(u);
|
|
672
|
+
function isMusl() {
|
|
673
|
+
if (fs5.existsSync("/etc/alpine-release"))
|
|
674
|
+
return true;
|
|
675
|
+
const r = spawnSync("ldd", ["--version"], { encoding: "utf8" });
|
|
676
|
+
return /musl/i.test(`${r.stdout ?? ""}${r.stderr ?? ""}`);
|
|
677
|
+
}
|
|
678
|
+
function platformKey() {
|
|
679
|
+
const os = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "darwin" : "linux";
|
|
680
|
+
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
|
|
681
|
+
return `${os}-${arch}${os === "linux" && isMusl() ? "-musl" : ""}`;
|
|
682
|
+
}
|
|
683
|
+
var ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
684
|
+
function valid(a) {
|
|
685
|
+
const x = a;
|
|
686
|
+
return !!x && typeof x.id === "string" && ID.test(x.id) && typeof x.name === "string" && typeof x.version === "string" && !!x.distribution && typeof x.distribution === "object";
|
|
687
|
+
}
|
|
688
|
+
async function fetchRegistry() {
|
|
689
|
+
const u = registryUrl();
|
|
690
|
+
const text = u.startsWith("file:") ? fs5.readFileSync(new URL(u), "utf8") : await (await fetch(u, { signal: AbortSignal.timeout(20000) })).text();
|
|
691
|
+
const j = JSON.parse(text);
|
|
692
|
+
const local = isLocalRegistry(u);
|
|
693
|
+
return (Array.isArray(j.agents) ? j.agents : []).filter(valid).map((a) => local ? a : { ...a, distribution: { ...a.distribution, local: undefined } });
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// src/agent/session.ts
|
|
697
|
+
import crypto from "node:crypto";
|
|
698
|
+
import fs6 from "node:fs";
|
|
699
|
+
import path3 from "node:path";
|
|
700
|
+
|
|
701
|
+
// src/agent/acp.ts
|
|
702
|
+
import { spawn } from "node:child_process";
|
|
635
703
|
import { EventEmitter } from "node:events";
|
|
704
|
+
import readline from "node:readline";
|
|
705
|
+
class RpcError extends Error {
|
|
706
|
+
code;
|
|
707
|
+
data;
|
|
708
|
+
constructor(code, message, data) {
|
|
709
|
+
super(message);
|
|
710
|
+
this.code = code;
|
|
711
|
+
this.data = data;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
class AcpProcess extends EventEmitter {
|
|
716
|
+
child;
|
|
717
|
+
nextId = 1;
|
|
718
|
+
pending = new Map;
|
|
719
|
+
stderrTail = "";
|
|
720
|
+
onRequest = async (method) => {
|
|
721
|
+
throw new RpcError(-32601, `Method not found: ${method}`);
|
|
722
|
+
};
|
|
723
|
+
onNotification = () => {
|
|
724
|
+
return;
|
|
725
|
+
};
|
|
726
|
+
get alive() {
|
|
727
|
+
return !!this.child && this.child.exitCode === null && !this.child.killed;
|
|
728
|
+
}
|
|
729
|
+
get stderr() {
|
|
730
|
+
return this.stderrTail;
|
|
731
|
+
}
|
|
732
|
+
async start(agent, cwd, env = {}, timeoutMs = 180000) {
|
|
733
|
+
const child = spawn(agent.launch.cmd, agent.launch.args, { cwd, env: { ...process.env, ...agent.launch.env, ...env }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
734
|
+
this.child = child;
|
|
735
|
+
child.stderr?.on("data", (d) => this.stderrTail = (this.stderrTail + d).slice(-4096));
|
|
736
|
+
child.stdin?.on("error", () => {
|
|
737
|
+
return;
|
|
738
|
+
});
|
|
739
|
+
readline.createInterface({ input: child.stdout }).on("line", (line) => this.receive(line));
|
|
740
|
+
child.on("error", (e) => this.finish(e));
|
|
741
|
+
child.on("exit", (code) => this.finish(null, code));
|
|
742
|
+
return this.request("initialize", {
|
|
743
|
+
protocolVersion: 1,
|
|
744
|
+
clientCapabilities: { auth: { terminal: true }, fs: { readTextFile: true, writeTextFile: true }, terminal: false },
|
|
745
|
+
clientInfo: { name: "hypeframe", title: "HypeFrame", version: VERSION }
|
|
746
|
+
}, timeoutMs);
|
|
747
|
+
}
|
|
748
|
+
exited = false;
|
|
749
|
+
finish(err, code = null) {
|
|
750
|
+
if (this.exited)
|
|
751
|
+
return;
|
|
752
|
+
this.exited = true;
|
|
753
|
+
const e = err ?? new Error(`Agent stopped (exit ${code})`);
|
|
754
|
+
for (const p of this.pending.values())
|
|
755
|
+
p.fail(e);
|
|
756
|
+
this.pending.clear();
|
|
757
|
+
this.emit("exit", err ? -1 : code);
|
|
758
|
+
}
|
|
759
|
+
send(m) {
|
|
760
|
+
if (this.child?.stdin?.writable)
|
|
761
|
+
this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}
|
|
762
|
+
`);
|
|
763
|
+
}
|
|
764
|
+
request(method, params, timeoutMs) {
|
|
765
|
+
if (this.exited)
|
|
766
|
+
return Promise.reject(new Error("Agent stopped"));
|
|
767
|
+
const id = this.nextId++;
|
|
768
|
+
return new Promise((ok, fail) => {
|
|
769
|
+
let timer;
|
|
770
|
+
const done = (f) => (v) => (clearTimeout(timer), f(v));
|
|
771
|
+
this.pending.set(id, { ok: done(ok), fail: done(fail) });
|
|
772
|
+
if (timeoutMs)
|
|
773
|
+
timer = setTimeout(() => {
|
|
774
|
+
if (!this.pending.delete(id))
|
|
775
|
+
return;
|
|
776
|
+
fail(new Error(`${method} took longer than ${Math.round(timeoutMs / 1000)} s`));
|
|
777
|
+
}, timeoutMs);
|
|
778
|
+
this.send({ id, method, params });
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
notify(method, params) {
|
|
782
|
+
this.send({ method, params });
|
|
783
|
+
}
|
|
784
|
+
receive(line) {
|
|
785
|
+
let m;
|
|
786
|
+
try {
|
|
787
|
+
m = JSON.parse(line);
|
|
788
|
+
} catch {
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
if (!m || typeof m !== "object")
|
|
792
|
+
return;
|
|
793
|
+
if (m.method === undefined && m.id !== undefined) {
|
|
794
|
+
const p = this.pending.get(m.id);
|
|
795
|
+
if (!p)
|
|
796
|
+
return;
|
|
797
|
+
this.pending.delete(m.id);
|
|
798
|
+
if (m.error)
|
|
799
|
+
p.fail(new RpcError(Number(m.error.code) || -32000, String(m.error.message || "error"), m.error.data));
|
|
800
|
+
else
|
|
801
|
+
p.ok(m.result);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
if (typeof m.method !== "string")
|
|
805
|
+
return;
|
|
806
|
+
if (m.id === undefined || m.id === null)
|
|
807
|
+
return this.onNotification(m.method, m.params);
|
|
808
|
+
this.onRequest(m.method, m.params).then((result) => this.send({ id: m.id, result: result ?? null }), (e) => this.send({ id: m.id, error: { code: e instanceof RpcError ? e.code : -32603, message: e instanceof Error ? e.message : String(e) } }));
|
|
809
|
+
}
|
|
810
|
+
stop() {
|
|
811
|
+
if (!this.child || this.exited)
|
|
812
|
+
return Promise.resolve();
|
|
813
|
+
return new Promise((ok) => {
|
|
814
|
+
const t = setTimeout(ok, 3000);
|
|
815
|
+
this.once("exit", () => (clearTimeout(t), ok()));
|
|
816
|
+
const pid = this.child?.pid;
|
|
817
|
+
if (process.platform === "win32" && pid) {
|
|
818
|
+
const k = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
|
|
819
|
+
k.on("error", () => this.child?.kill());
|
|
820
|
+
} else
|
|
821
|
+
this.child?.kill();
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// src/agent/session.ts
|
|
827
|
+
var UNSAFE_MODE = /bypass|dont.?ask|accept.?edits|yolo|full.?access|danger/i;
|
|
828
|
+
var SAFE_MODES = ["default", "ask"];
|
|
829
|
+
var MAX_READ = 10 * 1024 * 1024;
|
|
830
|
+
var MAX_OPTIONS = 48 * 1024;
|
|
831
|
+
var isModeOption = (c) => !!c && (c.category === "mode" || /mode/i.test(String(c.id ?? "")));
|
|
832
|
+
var safeConfig = (list) => list.filter((c) => c && typeof c === "object").map((c) => isModeOption(c) && Array.isArray(c.options) ? { ...c, options: c.options.filter((o) => !UNSAFE_MODE.test(String(o?.value ?? ""))) } : c);
|
|
833
|
+
function safeOptions(raw) {
|
|
834
|
+
const out = {};
|
|
835
|
+
if (Array.isArray(raw?.models?.availableModels) && raw.models.availableModels.length)
|
|
836
|
+
out.models = raw.models;
|
|
837
|
+
if (Array.isArray(raw?.modes?.availableModes) && raw.modes.availableModes.length)
|
|
838
|
+
out.modes = { ...raw.modes, availableModes: raw.modes.availableModes.filter((m) => !UNSAFE_MODE.test(String(m?.id ?? ""))) };
|
|
839
|
+
if (Array.isArray(raw?.configOptions))
|
|
840
|
+
out.configOptions = safeConfig(raw.configOptions);
|
|
841
|
+
return Buffer.byteLength(JSON.stringify(out)) > MAX_OPTIONS ? {} : out;
|
|
842
|
+
}
|
|
843
|
+
function splitId(id) {
|
|
844
|
+
const i = id.indexOf("/");
|
|
845
|
+
return i > 0 ? [id.slice(0, i), id.slice(i + 1)] : ["", id];
|
|
846
|
+
}
|
|
847
|
+
var lexists = (p) => {
|
|
848
|
+
try {
|
|
849
|
+
fs6.lstatSync(p);
|
|
850
|
+
return true;
|
|
851
|
+
} catch {
|
|
852
|
+
return false;
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
function insideFolder(folder, p) {
|
|
856
|
+
if (typeof p !== "string" || !p)
|
|
857
|
+
return false;
|
|
858
|
+
const abs = path3.resolve(folder, p);
|
|
859
|
+
const rel = path3.relative(folder, abs);
|
|
860
|
+
if (rel.startsWith("..") || path3.isAbsolute(rel))
|
|
861
|
+
return false;
|
|
862
|
+
let probe = abs;
|
|
863
|
+
while (!lexists(probe) && path3.dirname(probe) !== probe)
|
|
864
|
+
probe = path3.dirname(probe);
|
|
865
|
+
try {
|
|
866
|
+
const r = path3.relative(fs6.realpathSync(folder), fs6.realpathSync(probe));
|
|
867
|
+
return !(r.startsWith("..") || path3.isAbsolute(r));
|
|
868
|
+
} catch {
|
|
869
|
+
return false;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
var OUTSIDE = "Path outside the HypeFrame project folder";
|
|
873
|
+
|
|
874
|
+
class AgentSessions {
|
|
875
|
+
o;
|
|
876
|
+
procs = new Map;
|
|
877
|
+
starting = new Map;
|
|
878
|
+
sessions = new Map;
|
|
879
|
+
prompting = new Set;
|
|
880
|
+
constructor(o) {
|
|
881
|
+
this.o = o;
|
|
882
|
+
}
|
|
883
|
+
running() {
|
|
884
|
+
return [...this.procs.keys()];
|
|
885
|
+
}
|
|
886
|
+
process(agentId) {
|
|
887
|
+
const ada = this.procs.get(agentId);
|
|
888
|
+
if (ada?.proc.alive)
|
|
889
|
+
return Promise.resolve(ada);
|
|
890
|
+
const busy = this.starting.get(agentId);
|
|
891
|
+
if (busy)
|
|
892
|
+
return busy;
|
|
893
|
+
const agent = this.o.agent(agentId);
|
|
894
|
+
if (!agent)
|
|
895
|
+
return Promise.reject(new Error(`Agent ${agentId} is not installed`));
|
|
896
|
+
const proc = new AcpProcess;
|
|
897
|
+
proc.onRequest = (m, p) => this.fromAgent(agentId, m, p);
|
|
898
|
+
proc.onNotification = (m, p) => {
|
|
899
|
+
if (m === "session/update")
|
|
900
|
+
this.queue(`${agentId}/${String(p?.sessionId ?? "")}`, p?.update);
|
|
901
|
+
};
|
|
902
|
+
proc.on("exit", (code) => {
|
|
903
|
+
if (this.procs.get(agentId)?.proc === proc)
|
|
904
|
+
this.procs.delete(agentId);
|
|
905
|
+
for (const [id, s] of this.sessions)
|
|
906
|
+
if (s.agentId === agentId) {
|
|
907
|
+
this.flush(id);
|
|
908
|
+
this.sessions.delete(id);
|
|
909
|
+
}
|
|
910
|
+
this.o.onExit(agentId, code);
|
|
911
|
+
});
|
|
912
|
+
const cwd = path3.join(agentDir(), agentId, "kerja");
|
|
913
|
+
fs6.mkdirSync(cwd, { recursive: true });
|
|
914
|
+
const p = proc.start(agent, cwd, this.o.env?.(agentId) ?? {}, this.o.startTimeoutMs ?? 180000).then((init) => {
|
|
915
|
+
const entry = { proc, init };
|
|
916
|
+
this.procs.set(agentId, entry);
|
|
917
|
+
return entry;
|
|
918
|
+
}).catch(async (e) => {
|
|
919
|
+
await proc.stop();
|
|
920
|
+
throw e;
|
|
921
|
+
}).finally(() => this.starting.delete(agentId));
|
|
922
|
+
this.starting.set(agentId, p);
|
|
923
|
+
return p;
|
|
924
|
+
}
|
|
925
|
+
async open({ agentId, projectId, resumeId }) {
|
|
926
|
+
const { proc, init } = await this.process(agentId);
|
|
927
|
+
const [resumeAgent, resumeOwn] = resumeId ? splitId(resumeId) : ["", ""];
|
|
928
|
+
const resume = resumeOwn && (!resumeAgent || resumeAgent === agentId) ? resumeOwn : "";
|
|
929
|
+
const key = (own) => `${agentId}/${own}`;
|
|
930
|
+
const live = resume ? this.sessions.get(key(resume)) : undefined;
|
|
931
|
+
if (live)
|
|
932
|
+
return { sessionId: key(resume), init, raw: {}, dimuat: "hidup", routeId: live.routeId, opsi: live.opsi ?? {} };
|
|
933
|
+
const cwd = projectDir(projectId);
|
|
934
|
+
fs6.writeFileSync(path3.join(cwd, "AGENTS.md"), AGENTS_MD);
|
|
935
|
+
const routeId = crypto.randomBytes(9).toString("base64url");
|
|
936
|
+
const params = { cwd, mcpServers: this.o.mcpServers(cwd, projectId, routeId) };
|
|
937
|
+
const limit = this.o.sessionTimeoutMs ?? 90000;
|
|
938
|
+
let raw;
|
|
939
|
+
let dimuat = "baru";
|
|
940
|
+
if (resume && init.agentCapabilities?.loadSession) {
|
|
941
|
+
const s = { agentId, id: resume, cwd, routeId, buffer: [], loading: true };
|
|
942
|
+
this.sessions.set(key(resume), s);
|
|
943
|
+
try {
|
|
944
|
+
raw = { ...await proc.request("session/load", { ...params, sessionId: resume }, limit) ?? {}, sessionId: resume };
|
|
945
|
+
dimuat = "load";
|
|
946
|
+
this.flush(key(resume));
|
|
947
|
+
s.loading = false;
|
|
948
|
+
} catch {
|
|
949
|
+
this.sessions.delete(key(resume));
|
|
950
|
+
raw = undefined;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
try {
|
|
954
|
+
raw ??= await proc.request("session/new", params, limit);
|
|
955
|
+
} catch (e) {
|
|
956
|
+
if (/took longer/.test(e.message))
|
|
957
|
+
await proc.stop();
|
|
958
|
+
throw e;
|
|
959
|
+
}
|
|
960
|
+
const own = String(raw?.sessionId ?? "");
|
|
961
|
+
if (!own)
|
|
962
|
+
throw new Error("The agent did not create a session");
|
|
963
|
+
let s = this.sessions.get(key(own));
|
|
964
|
+
if (!s)
|
|
965
|
+
this.sessions.set(key(own), s = { agentId, id: own, cwd, routeId, buffer: [] });
|
|
966
|
+
const opsi = safeOptions(raw);
|
|
967
|
+
const mode = await this.safeMode(proc, own, raw);
|
|
968
|
+
if (mode && opsi.modes)
|
|
969
|
+
opsi.modes = { ...opsi.modes, currentModeId: mode };
|
|
970
|
+
s.opsi = opsi;
|
|
971
|
+
return { sessionId: key(own), init, raw, dimuat, routeId, opsi };
|
|
972
|
+
}
|
|
973
|
+
async safeMode(proc, own, raw) {
|
|
974
|
+
const current = String(raw?.modes?.currentModeId ?? "");
|
|
975
|
+
const available = Array.isArray(raw?.modes?.availableModes) ? raw.modes.availableModes.map((m) => String(m?.id ?? "")) : [];
|
|
976
|
+
let switched;
|
|
977
|
+
if (current && UNSAFE_MODE.test(current)) {
|
|
978
|
+
const target = SAFE_MODES.find((m) => available.includes(m));
|
|
979
|
+
if (target && await proc.request("session/set_mode", { sessionId: own, modeId: target }, 15000).then(() => true, () => false))
|
|
980
|
+
switched = target;
|
|
981
|
+
}
|
|
982
|
+
for (const c of Array.isArray(raw?.configOptions) ? raw.configOptions : []) {
|
|
983
|
+
if (!isModeOption(c) || !UNSAFE_MODE.test(String(c.currentValue ?? "")))
|
|
984
|
+
continue;
|
|
985
|
+
const values = (c.options ?? []).map((o) => String(o?.value ?? ""));
|
|
986
|
+
const target = SAFE_MODES.find((m) => values.includes(m));
|
|
987
|
+
if (target)
|
|
988
|
+
await proc.request("session/set_config_option", { sessionId: own, configId: String(c.id), value: target }, 15000).catch(() => {
|
|
989
|
+
return;
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
return switched;
|
|
993
|
+
}
|
|
994
|
+
async setOption(sessionId, o) {
|
|
995
|
+
const s = this.sessions.get(sessionId);
|
|
996
|
+
if (!s)
|
|
997
|
+
throw new Error("Unknown session");
|
|
998
|
+
const e = this.procs.get(s.agentId);
|
|
999
|
+
if (!e)
|
|
1000
|
+
throw new Error("Agent stopped");
|
|
1001
|
+
const id = String(o.id ?? "").slice(0, 100);
|
|
1002
|
+
const value = String(o.nilai ?? "").slice(0, 200);
|
|
1003
|
+
const config = s.opsi?.configOptions?.find((c) => c.id === id);
|
|
1004
|
+
const modeLike = o.jenis === "mode" || o.jenis !== "model" && (isModeOption(config) || /mode/i.test(id));
|
|
1005
|
+
if (modeLike && UNSAFE_MODE.test(value))
|
|
1006
|
+
throw new Error("A mode that skips asking is not allowed in HypeFrame");
|
|
1007
|
+
if (o.jenis === "model")
|
|
1008
|
+
return await e.proc.request("session/set_model", { sessionId: s.id, modelId: value }, 15000), {};
|
|
1009
|
+
if (o.jenis === "mode")
|
|
1010
|
+
return await e.proc.request("session/set_mode", { sessionId: s.id, modeId: value }, 15000), {};
|
|
1011
|
+
const r = await e.proc.request("session/set_config_option", { sessionId: s.id, configId: id, value }, 15000);
|
|
1012
|
+
if (!Array.isArray(r?.configOptions))
|
|
1013
|
+
return {};
|
|
1014
|
+
const configOptions = safeConfig(r.configOptions);
|
|
1015
|
+
s.opsi = { ...s.opsi, configOptions };
|
|
1016
|
+
return { configOptions };
|
|
1017
|
+
}
|
|
1018
|
+
agentOf(sessionId) {
|
|
1019
|
+
return this.sessions.get(sessionId)?.agentId ?? null;
|
|
1020
|
+
}
|
|
1021
|
+
busy(sessionId) {
|
|
1022
|
+
return this.prompting.has(sessionId);
|
|
1023
|
+
}
|
|
1024
|
+
async prompt(sessionId, text) {
|
|
1025
|
+
const s = this.sessions.get(sessionId);
|
|
1026
|
+
if (!s)
|
|
1027
|
+
throw new Error("Unknown session");
|
|
1028
|
+
const e = this.procs.get(s.agentId);
|
|
1029
|
+
if (!e)
|
|
1030
|
+
throw new Error("Agent stopped");
|
|
1031
|
+
this.prompting.add(sessionId);
|
|
1032
|
+
try {
|
|
1033
|
+
return await e.proc.request("session/prompt", { sessionId: s.id, prompt: [{ type: "text", text }] });
|
|
1034
|
+
} finally {
|
|
1035
|
+
this.prompting.delete(sessionId);
|
|
1036
|
+
this.flush(sessionId);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
cancel(sessionId) {
|
|
1040
|
+
const s = this.sessions.get(sessionId);
|
|
1041
|
+
if (s)
|
|
1042
|
+
this.procs.get(s.agentId)?.proc.notify("session/cancel", { sessionId: s.id });
|
|
1043
|
+
}
|
|
1044
|
+
async stopAll() {
|
|
1045
|
+
await Promise.all([...this.procs.values()].map(({ proc }) => proc.stop()));
|
|
1046
|
+
}
|
|
1047
|
+
queue(sessionId, update) {
|
|
1048
|
+
const s = this.sessions.get(sessionId);
|
|
1049
|
+
if (!s || update === undefined)
|
|
1050
|
+
return;
|
|
1051
|
+
s.buffer.push(update);
|
|
1052
|
+
s.timer ??= setTimeout(() => this.flush(sessionId), this.o.flushMs ?? 100);
|
|
1053
|
+
}
|
|
1054
|
+
flush(sessionId) {
|
|
1055
|
+
const s = this.sessions.get(sessionId);
|
|
1056
|
+
if (!s)
|
|
1057
|
+
return;
|
|
1058
|
+
clearTimeout(s.timer);
|
|
1059
|
+
s.timer = undefined;
|
|
1060
|
+
if (s.buffer.length)
|
|
1061
|
+
this.o.onUpdate(sessionId, s.buffer.splice(0), { replay: !!s.loading });
|
|
1062
|
+
}
|
|
1063
|
+
async fromAgent(agentId, method, raw) {
|
|
1064
|
+
const key = `${agentId}/${String(raw?.sessionId ?? "")}`;
|
|
1065
|
+
const s = this.sessions.get(key);
|
|
1066
|
+
if (!s)
|
|
1067
|
+
throw new RpcError(-32602, "Unknown session");
|
|
1068
|
+
const p = { ...raw, sessionId: key };
|
|
1069
|
+
if (method === "session/request_permission") {
|
|
1070
|
+
const options = Array.isArray(p.options) ? p.options : [];
|
|
1071
|
+
const reject = options.find((o) => String(o.kind).startsWith("reject"));
|
|
1072
|
+
const refuse = () => reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
|
|
1073
|
+
const locations = Array.isArray(p.toolCall?.locations) ? p.toolCall.locations : [];
|
|
1074
|
+
if (locations.some((l) => !insideFolder(s.cwd, l?.path)))
|
|
1075
|
+
return refuse();
|
|
1076
|
+
this.flush(String(p.sessionId));
|
|
1077
|
+
let timer;
|
|
1078
|
+
const choice = await Promise.race([
|
|
1079
|
+
this.o.onPermission(String(p.sessionId), { sessionId: String(p.sessionId), toolCall: p.toolCall ?? {}, options }, { mustAsk: locations.length === 0 }),
|
|
1080
|
+
new Promise((ok) => timer = setTimeout(() => ok(null), this.o.permissionTimeoutMs ?? 5 * 60000))
|
|
1081
|
+
]).finally(() => clearTimeout(timer));
|
|
1082
|
+
return choice && options.some((o) => o.optionId === choice) ? { outcome: { outcome: "selected", optionId: choice } } : refuse();
|
|
1083
|
+
}
|
|
1084
|
+
if (method === "fs/read_text_file") {
|
|
1085
|
+
if (!insideFolder(s.cwd, p.path))
|
|
1086
|
+
throw new RpcError(-32602, OUTSIDE);
|
|
1087
|
+
const st = fs6.statSync(path3.resolve(s.cwd, p.path), { throwIfNoEntry: false });
|
|
1088
|
+
if (!st?.isFile())
|
|
1089
|
+
throw new RpcError(-32602, "Not a regular file");
|
|
1090
|
+
if (st.size > MAX_READ)
|
|
1091
|
+
throw new RpcError(-32602, "File too large (over 10 MB)");
|
|
1092
|
+
let content = fs6.readFileSync(path3.resolve(s.cwd, p.path), "utf8");
|
|
1093
|
+
if (p.line || p.limit) {
|
|
1094
|
+
const lines = content.split(`
|
|
1095
|
+
`);
|
|
1096
|
+
const from = Math.max(0, (Number(p.line) || 1) - 1);
|
|
1097
|
+
content = lines.slice(from, p.limit ? from + Number(p.limit) : undefined).join(`
|
|
1098
|
+
`);
|
|
1099
|
+
}
|
|
1100
|
+
return { content };
|
|
1101
|
+
}
|
|
1102
|
+
if (method === "fs/write_text_file") {
|
|
1103
|
+
if (!insideFolder(s.cwd, p.path))
|
|
1104
|
+
throw new RpcError(-32602, OUTSIDE);
|
|
1105
|
+
const f = path3.resolve(s.cwd, p.path);
|
|
1106
|
+
fs6.mkdirSync(path3.dirname(f), { recursive: true });
|
|
1107
|
+
fs6.writeFileSync(f, String(p.content ?? ""));
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
throw new RpcError(-32601, `Method not found: ${method}`);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// src/agent/store.ts
|
|
1115
|
+
import fs7 from "node:fs";
|
|
1116
|
+
import path4 from "node:path";
|
|
1117
|
+
function setReady(id, ready) {
|
|
1118
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
1119
|
+
if (a)
|
|
1120
|
+
writeInstalled({ ...a, ready });
|
|
1121
|
+
}
|
|
1122
|
+
var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
1123
|
+
var folder = (id) => {
|
|
1124
|
+
if (typeof id !== "string" || !AGENT_ID.test(id))
|
|
1125
|
+
throw new Error(`Invalid agent id: ${JSON.stringify(String(id)).slice(0, 60)}`);
|
|
1126
|
+
return path4.join(agentDir(), id);
|
|
1127
|
+
};
|
|
1128
|
+
function readInstalled() {
|
|
1129
|
+
const out = [];
|
|
1130
|
+
for (const id of fs7.readdirSync(agentDir())) {
|
|
1131
|
+
if (!AGENT_ID.test(id))
|
|
1132
|
+
continue;
|
|
1133
|
+
try {
|
|
1134
|
+
const a = JSON.parse(fs7.readFileSync(path4.join(folder(id), "agent.json"), "utf8"));
|
|
1135
|
+
if (a.id === id && a.launch?.cmd)
|
|
1136
|
+
out.push(a);
|
|
1137
|
+
} catch {}
|
|
1138
|
+
}
|
|
1139
|
+
return out;
|
|
1140
|
+
}
|
|
1141
|
+
function writeInstalled(a) {
|
|
1142
|
+
fs7.mkdirSync(folder(a.id), { recursive: true });
|
|
1143
|
+
const f = path4.join(folder(a.id), "agent.json");
|
|
1144
|
+
fs7.writeFileSync(`${f}.tmp`, JSON.stringify(a, null, 2));
|
|
1145
|
+
fs7.renameSync(`${f}.tmp`, f);
|
|
1146
|
+
}
|
|
1147
|
+
function removeAgent(id) {
|
|
1148
|
+
fs7.rmSync(folder(id), { recursive: true, force: true });
|
|
1149
|
+
}
|
|
1150
|
+
function agentEnv(id) {
|
|
1151
|
+
try {
|
|
1152
|
+
return JSON.parse(fs7.readFileSync(path4.join(folder(id), "env.json"), "utf8"));
|
|
1153
|
+
} catch {
|
|
1154
|
+
return {};
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function saveAgentEnv(id, env) {
|
|
1158
|
+
fs7.mkdirSync(folder(id), { recursive: true });
|
|
1159
|
+
const f = path4.join(folder(id), "env.json");
|
|
1160
|
+
fs7.writeFileSync(`${f}.tmp`, JSON.stringify({ ...agentEnv(id), ...env }), { mode: 384 });
|
|
1161
|
+
fs7.renameSync(`${f}.tmp`, f);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// src/agent/service.ts
|
|
1165
|
+
var MAX_NEWS = 180 * 1024;
|
|
1166
|
+
var MAX_TOOL_ARGS = 200 * 1024;
|
|
1167
|
+
var MAX_TEXT = 48 * 1024;
|
|
1168
|
+
var NOT_OPEN = "HypeFrame Web is not open (the tab that started this chat was closed or reloaded). Ask the user to open HypeFrame Web and send the message again.";
|
|
1169
|
+
var ERRORS = {
|
|
1170
|
+
tab: NOT_OPEN,
|
|
1171
|
+
terputus: "The HypeFrame engine is offline right now. Try again in a moment.",
|
|
1172
|
+
waktu: "HypeFrame Web did not answer in time. Make sure the HypeFrame Web tab is open, then try again."
|
|
1173
|
+
};
|
|
1174
|
+
var MAX_HISTORY = 2 * 1024 * 1024;
|
|
1175
|
+
var HISTORY_ANSWER = 170 * 1024;
|
|
1176
|
+
var MAX_FILE2 = 4 * 1024 * 1024;
|
|
1177
|
+
var PIECE = 150 * 1024;
|
|
1178
|
+
var MEDIA = {
|
|
1179
|
+
png: "image/png",
|
|
1180
|
+
jpg: "image/jpeg",
|
|
1181
|
+
jpeg: "image/jpeg",
|
|
1182
|
+
webp: "image/webp",
|
|
1183
|
+
gif: "image/gif",
|
|
1184
|
+
svg: "image/svg+xml",
|
|
1185
|
+
mp3: "audio/mpeg",
|
|
1186
|
+
wav: "audio/wav",
|
|
1187
|
+
ogg: "audio/ogg",
|
|
1188
|
+
m4a: "audio/mp4",
|
|
1189
|
+
aac: "audio/aac",
|
|
1190
|
+
mp4: "video/mp4",
|
|
1191
|
+
webm: "video/webm",
|
|
1192
|
+
mov: "video/quicktime",
|
|
1193
|
+
json: "application/json",
|
|
1194
|
+
lottie: "application/zip",
|
|
1195
|
+
ttf: "font/ttf",
|
|
1196
|
+
otf: "font/otf",
|
|
1197
|
+
woff: "font/woff",
|
|
1198
|
+
woff2: "font/woff2"
|
|
1199
|
+
};
|
|
1200
|
+
var FILE_TOOL = {
|
|
1201
|
+
name: "add_file_from_computer",
|
|
1202
|
+
description: "Add a file from the HypeFrame project folder on this computer (your working folder) to the HypeFrame project open in the web, as a project asset. Use it for images, audio, video, fonts or Lottie/JSON files you created or downloaded there. Files up to 4 MB. Returns the asset id to use in motion code as asset://<id>.",
|
|
1203
|
+
inputSchema: { type: "object", properties: { path: { type: "string", description: "Path of the file, relative to the project folder (or absolute inside it)." } }, required: ["path"] }
|
|
1204
|
+
};
|
|
1205
|
+
var bytes = (v) => Buffer.byteLength(JSON.stringify(v) ?? "");
|
|
1206
|
+
var cut = (s, n) => typeof s === "string" ? s.length > n ? `${s.slice(0, n)}…` : s : undefined;
|
|
1207
|
+
var isChunk = (x) => !!x && (x.sessionUpdate === "agent_message_chunk" || x.sessionUpdate === "agent_thought_chunk" || x.sessionUpdate === "user_message_chunk") && x.content?.type === "text";
|
|
1208
|
+
function slimTool(u) {
|
|
1209
|
+
const texts = (Array.isArray(u.content) ? u.content : []).map((c) => c?.content?.type === "text" ? String(c.content.text ?? "") : c?.type === "text" ? String(c.text ?? "") : "").filter(Boolean).join(" ");
|
|
1210
|
+
const out = { sessionUpdate: u.sessionUpdate, toolCallId: u.toolCallId };
|
|
1211
|
+
for (const k of ["title", "status", "kind"])
|
|
1212
|
+
if (typeof u[k] === "string")
|
|
1213
|
+
out[k] = cut(u[k], 300);
|
|
1214
|
+
if (texts)
|
|
1215
|
+
out.content = [{ type: "content", content: { type: "text", text: cut(texts, 400) } }];
|
|
1216
|
+
return out;
|
|
1217
|
+
}
|
|
1218
|
+
function slim(raw) {
|
|
1219
|
+
if (!raw || typeof raw !== "object")
|
|
1220
|
+
return [];
|
|
1221
|
+
const u = raw;
|
|
1222
|
+
if (isChunk(u)) {
|
|
1223
|
+
const t = String(u.content.text ?? "");
|
|
1224
|
+
const out = [];
|
|
1225
|
+
for (let i = 0;i < t.length || i === 0; i += MAX_TEXT)
|
|
1226
|
+
out.push({ sessionUpdate: u.sessionUpdate, content: { type: "text", text: t.slice(i, i + MAX_TEXT) } });
|
|
1227
|
+
return out;
|
|
1228
|
+
}
|
|
1229
|
+
if (u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update")
|
|
1230
|
+
return [slimTool(u)];
|
|
1231
|
+
if (u.sessionUpdate === "agent_message_chunk" || u.sessionUpdate === "agent_thought_chunk")
|
|
1232
|
+
return [];
|
|
1233
|
+
return bytes(u) > 64 * 1024 ? [] : [u];
|
|
1234
|
+
}
|
|
1235
|
+
function packUpdates(list) {
|
|
1236
|
+
const merged = [];
|
|
1237
|
+
for (const u of list.flatMap(slim)) {
|
|
1238
|
+
const last = merged[merged.length - 1];
|
|
1239
|
+
if (isChunk(u) && isChunk(last) && last.sessionUpdate === u.sessionUpdate && String(last.content.text).length + String(u.content.text).length <= MAX_TEXT)
|
|
1240
|
+
last.content = { type: "text", text: `${last.content.text}${u.content.text}` };
|
|
1241
|
+
else
|
|
1242
|
+
merged.push(isChunk(u) ? { ...u, content: { ...u.content } } : u);
|
|
1243
|
+
}
|
|
1244
|
+
const parts = [];
|
|
1245
|
+
let part = [];
|
|
1246
|
+
let size = 0;
|
|
1247
|
+
for (const u of merged) {
|
|
1248
|
+
const n = bytes(u) + 1;
|
|
1249
|
+
if (n > MAX_NEWS - 1024)
|
|
1250
|
+
continue;
|
|
1251
|
+
if (part.length && size + n > MAX_NEWS - 1024)
|
|
1252
|
+
parts.push(part), part = [], size = 0;
|
|
1253
|
+
part.push(u);
|
|
1254
|
+
size += n;
|
|
1255
|
+
}
|
|
1256
|
+
if (part.length)
|
|
1257
|
+
parts.push(part);
|
|
1258
|
+
return parts;
|
|
1259
|
+
}
|
|
1260
|
+
function commandText(req) {
|
|
1261
|
+
if (req.toolCall.kind !== "execute")
|
|
1262
|
+
return;
|
|
1263
|
+
const c = req.toolCall.rawInput?.command;
|
|
1264
|
+
if (Array.isArray(c))
|
|
1265
|
+
return c.map((a) => typeof a === "string" && /^[\w@%+=:,./-]+$/.test(a) ? a : JSON.stringify(String(a))).join(" ");
|
|
1266
|
+
return typeof c === "string" ? c : String(req.toolCall.title ?? "");
|
|
1267
|
+
}
|
|
1268
|
+
function historyFile(projectId, sessionId) {
|
|
1269
|
+
return path5.join(projectDir(projectId), "riwayat", `${crypto2.createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}.jsonl`);
|
|
1270
|
+
}
|
|
1271
|
+
function record(file, updates) {
|
|
1272
|
+
if (!updates.length)
|
|
1273
|
+
return;
|
|
1274
|
+
try {
|
|
1275
|
+
fs8.mkdirSync(path5.dirname(file), { recursive: true });
|
|
1276
|
+
fs8.appendFileSync(file, `${updates.map((u) => JSON.stringify(u)).join(`
|
|
1277
|
+
`)}
|
|
1278
|
+
`);
|
|
1279
|
+
if (fs8.statSync(file).size > MAX_HISTORY) {
|
|
1280
|
+
const text = fs8.readFileSync(file, "utf8");
|
|
1281
|
+
const from = text.indexOf(`
|
|
1282
|
+
`, text.length - MAX_HISTORY / 2);
|
|
1283
|
+
fs8.writeFileSync(file, from >= 0 ? text.slice(from + 1) : "");
|
|
1284
|
+
}
|
|
1285
|
+
} catch {}
|
|
1286
|
+
}
|
|
1287
|
+
function readHistory(file) {
|
|
1288
|
+
let text = "";
|
|
1289
|
+
try {
|
|
1290
|
+
text = fs8.readFileSync(file, "utf8");
|
|
1291
|
+
} catch {
|
|
1292
|
+
return { update: [], potong: false };
|
|
1293
|
+
}
|
|
1294
|
+
const out = [];
|
|
1295
|
+
let size = 0;
|
|
1296
|
+
const lines = text.split(`
|
|
1297
|
+
`).filter(Boolean);
|
|
1298
|
+
for (let i = lines.length - 1;i >= 0; i--) {
|
|
1299
|
+
size += Buffer.byteLength(lines[i]) + 1;
|
|
1300
|
+
if (size > HISTORY_ANSWER)
|
|
1301
|
+
return { update: out.reverse(), potong: true };
|
|
1302
|
+
try {
|
|
1303
|
+
out.push(JSON.parse(lines[i]));
|
|
1304
|
+
} catch {}
|
|
1305
|
+
}
|
|
1306
|
+
return { update: out.reverse(), potong: false };
|
|
1307
|
+
}
|
|
1308
|
+
function createAgentService(o) {
|
|
1309
|
+
const key = crypto2.randomBytes(24).toString("base64url");
|
|
1310
|
+
const routes = new Map;
|
|
1311
|
+
const sessionRoute = new Map;
|
|
1312
|
+
const permissions = new Map;
|
|
1313
|
+
const histories = new Map;
|
|
1314
|
+
const pending = new Map;
|
|
1315
|
+
let turn = 0;
|
|
1316
|
+
const sendUpdates = (sessionId) => {
|
|
1317
|
+
const list = pending.get(sessionId);
|
|
1318
|
+
pending.delete(sessionId);
|
|
1319
|
+
if (!list?.length)
|
|
1320
|
+
return;
|
|
1321
|
+
const parts = packUpdates(list);
|
|
1322
|
+
o.conn.news("agen", { sessionId, update: parts.shift() ?? [] });
|
|
1323
|
+
if (parts.length)
|
|
1324
|
+
pending.set(sessionId, parts.flat());
|
|
1325
|
+
};
|
|
1326
|
+
const ticker = setInterval(() => {
|
|
1327
|
+
const ids = [...pending.keys()];
|
|
1328
|
+
if (ids.length)
|
|
1329
|
+
sendUpdates(ids[turn++ % ids.length]);
|
|
1330
|
+
}, o.newsMs ?? 400);
|
|
1331
|
+
ticker.unref?.();
|
|
1332
|
+
const control = (sessionId, body) => {
|
|
1333
|
+
while (pending.has(sessionId))
|
|
1334
|
+
sendUpdates(sessionId);
|
|
1335
|
+
o.conn.news("agen", { sessionId, ...body });
|
|
1336
|
+
};
|
|
1337
|
+
const sessions = new AgentSessions({
|
|
1338
|
+
agent: (id) => readInstalled().find((a) => a.id === id),
|
|
1339
|
+
env: (id) => agentEnv(id),
|
|
1340
|
+
mcpServers: (_cwd, projectId, routeId) => [
|
|
1341
|
+
{
|
|
1342
|
+
name: "hypeframe",
|
|
1343
|
+
command: o.bridge.command,
|
|
1344
|
+
args: o.bridge.args,
|
|
1345
|
+
env: [
|
|
1346
|
+
...o.bridge.env,
|
|
1347
|
+
{ name: "HF_MCP_URL", value: `http://127.0.0.1:${o.port()}/agen/mcp/${projectId}/${routeId}` },
|
|
1348
|
+
{ name: "HF_MCP_KUNCI", value: key }
|
|
1349
|
+
]
|
|
1350
|
+
}
|
|
1351
|
+
],
|
|
1352
|
+
onUpdate: (sessionId, list, info) => {
|
|
1353
|
+
const p = pending.get(sessionId);
|
|
1354
|
+
if (p)
|
|
1355
|
+
p.push(...list);
|
|
1356
|
+
else
|
|
1357
|
+
pending.set(sessionId, [...list]);
|
|
1358
|
+
const file = histories.get(sessionId);
|
|
1359
|
+
if (file && !info?.replay)
|
|
1360
|
+
record(file, packUpdates(list).flat());
|
|
1361
|
+
},
|
|
1362
|
+
onPermission: (sessionId, req, info) => new Promise((ok) => {
|
|
1363
|
+
const id = `i${crypto2.randomBytes(6).toString("hex")}`;
|
|
1364
|
+
const done = (v) => (permissions.delete(id), ok(v));
|
|
1365
|
+
permissions.set(id, done);
|
|
1366
|
+
setTimeout(() => permissions.has(id) && done(null), 5 * 60000).unref();
|
|
1367
|
+
control(sessionId, { izin: { id, judul: String(req.toolCall.title ?? ""), jenis: String(req.toolCall.kind ?? ""), perintah: commandText(req), wajibTanya: info.mustAsk, opsi: req.options } });
|
|
1368
|
+
}),
|
|
1369
|
+
onExit: (agentId, code) => o.conn.news("agen", { agentId, berhenti: code }),
|
|
1370
|
+
flushMs: o.flushMs ?? 100
|
|
1371
|
+
});
|
|
1372
|
+
const text = (c, k) => typeof c[k] === "string" ? c[k] : "";
|
|
1373
|
+
const work = {
|
|
1374
|
+
"agen.mulai": async (c) => {
|
|
1375
|
+
const agentId = text(c, "agentId");
|
|
1376
|
+
const projectId = text(c, "projectId");
|
|
1377
|
+
const tab = text(c, "tab");
|
|
1378
|
+
const a = readInstalled().find((x) => x.id === agentId);
|
|
1379
|
+
if (!a)
|
|
1380
|
+
throw new Error("Agen belum dipasang di mesin ini.");
|
|
1381
|
+
if (!a.ready)
|
|
1382
|
+
throw new Error("Agen belum masuk akun di mesin ini.");
|
|
1383
|
+
const { sessionId, dimuat, routeId, opsi } = await sessions.open({ agentId, projectId, resumeId: text(c, "resume") || undefined });
|
|
1384
|
+
const alat = Array.isArray(c.alat) ? c.alat : undefined;
|
|
1385
|
+
const r = routes.get(routeId);
|
|
1386
|
+
if (!r)
|
|
1387
|
+
routes.set(routeId, { dari: c.dari, tab, alat: alat ?? [], projectId });
|
|
1388
|
+
else {
|
|
1389
|
+
if (tab && r.tab === tab)
|
|
1390
|
+
r.dari = c.dari;
|
|
1391
|
+
if (alat)
|
|
1392
|
+
r.alat = alat;
|
|
1393
|
+
}
|
|
1394
|
+
sessionRoute.set(sessionId, routeId);
|
|
1395
|
+
histories.set(sessionId, historyFile(projectId, sessionId));
|
|
1396
|
+
return { sessionId, nama: a.name, sibuk: sessions.busy(sessionId), dimuat, opsi };
|
|
1397
|
+
},
|
|
1398
|
+
"agen.kirim": async (c) => {
|
|
1399
|
+
const sessionId = text(c, "sessionId");
|
|
1400
|
+
const routeId = sessionRoute.get(sessionId);
|
|
1401
|
+
if (!routeId || !sessions.agentOf(sessionId))
|
|
1402
|
+
throw new Error("Obrolan ini sudah berakhir. Mulai lagi.");
|
|
1403
|
+
if (sessions.busy(sessionId))
|
|
1404
|
+
throw new Error("Agen masih mengerjakan pesan sebelumnya.");
|
|
1405
|
+
const r = routes.get(routeId);
|
|
1406
|
+
if (r)
|
|
1407
|
+
r.dari = c.dari, r.tab = text(c, "tab") || r.tab;
|
|
1408
|
+
const file = histories.get(sessionId);
|
|
1409
|
+
if (file)
|
|
1410
|
+
record(file, packUpdates([{ sessionUpdate: "user_message_chunk", content: { type: "text", text: text(c, "teks") } }]).flat());
|
|
1411
|
+
sessions.prompt(sessionId, text(c, "teks")).then((res) => control(sessionId, { selesai: res.stopReason }), (e) => control(sessionId, { galat: e.message.slice(0, 300) }));
|
|
1412
|
+
return {};
|
|
1413
|
+
},
|
|
1414
|
+
"agen.izin": async (c) => {
|
|
1415
|
+
permissions.get(text(c, "izinId"))?.(typeof c.optionId === "string" ? c.optionId : null);
|
|
1416
|
+
return {};
|
|
1417
|
+
},
|
|
1418
|
+
"agen.batal": async (c) => {
|
|
1419
|
+
sessions.cancel(text(c, "sessionId"));
|
|
1420
|
+
return {};
|
|
1421
|
+
},
|
|
1422
|
+
"agen.opsi": async (c) => {
|
|
1423
|
+
const macam = text(c, "macam");
|
|
1424
|
+
if (!["model", "mode", "opsi"].includes(macam))
|
|
1425
|
+
throw new Error("Pilihan tidak dikenal.");
|
|
1426
|
+
return sessions.setOption(text(c, "sessionId"), { jenis: macam, id: text(c, "id"), nilai: text(c, "nilai") });
|
|
1427
|
+
},
|
|
1428
|
+
"agen.riwayat": async (c) => {
|
|
1429
|
+
try {
|
|
1430
|
+
return readHistory(historyFile(text(c, "projectId"), text(c, "sessionId")));
|
|
1431
|
+
} catch {
|
|
1432
|
+
return { update: [], potong: false };
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
async function sendFile(target, projectId, args) {
|
|
1437
|
+
const fail = (t) => ({ isError: true, content: [{ type: "text", text: t }] });
|
|
1438
|
+
const p = typeof args?.path === "string" ? String(args.path) : "";
|
|
1439
|
+
const folder = projectDir(projectId);
|
|
1440
|
+
if (!p || !insideFolder(folder, p))
|
|
1441
|
+
return fail(`Only files inside the HypeFrame project folder (${folder}) can be added.`);
|
|
1442
|
+
const file = path5.resolve(folder, p);
|
|
1443
|
+
const st = fs8.statSync(file, { throwIfNoEntry: false });
|
|
1444
|
+
if (!st?.isFile())
|
|
1445
|
+
return fail(`${p} is not a file in the project folder.`);
|
|
1446
|
+
const nama = path5.basename(file).slice(0, 120);
|
|
1447
|
+
const mime = MEDIA[path5.extname(file).slice(1).toLowerCase()];
|
|
1448
|
+
if (!mime)
|
|
1449
|
+
return fail(`${nama}: only images, audio, video, fonts and Lottie/JSON files can be added to a HypeFrame project.`);
|
|
1450
|
+
if (st.size > MAX_FILE2)
|
|
1451
|
+
return fail(`${nama} is ${(st.size / 1048576).toFixed(1)} MB; files up to 4 MB can be sent to HypeFrame Web. Make it smaller (lower resolution or bitrate) and try again.`);
|
|
1452
|
+
const data = fs8.readFileSync(file).toString("base64");
|
|
1453
|
+
const n = Math.max(1, Math.ceil(data.length / PIECE));
|
|
1454
|
+
const id = crypto2.randomBytes(8).toString("hex");
|
|
1455
|
+
let last = {};
|
|
1456
|
+
for (let i = 0;i < n; i++) {
|
|
1457
|
+
last = await o.conn.request(target.dari, "alat", { nama: "_berkas", arg: { id, i, n, nama, mime, ukuran: st.size, data: data.slice(i * PIECE, (i + 1) * PIECE) } });
|
|
1458
|
+
if (last.ok === false) {
|
|
1459
|
+
const error = String(last.error) in ERRORS ? String(last.error) : "tab";
|
|
1460
|
+
o.onToolError?.(error);
|
|
1461
|
+
return fail(ERRORS[error]);
|
|
1462
|
+
}
|
|
1463
|
+
if (last.isError)
|
|
1464
|
+
return { isError: true, content: Array.isArray(last.content) ? last.content : [] };
|
|
1465
|
+
}
|
|
1466
|
+
return { isError: false, content: Array.isArray(last.content) ? last.content : [] };
|
|
1467
|
+
}
|
|
1468
|
+
const reply = (res, status, body) => {
|
|
1469
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
1470
|
+
res.end(body === undefined ? "" : JSON.stringify(body));
|
|
1471
|
+
};
|
|
1472
|
+
async function route(req, res, url) {
|
|
1473
|
+
const m = url.pathname.match(/^\/agen\/mcp\/([A-Za-z0-9_-]{1,80})\/([A-Za-z0-9_-]{1,40})$/);
|
|
1474
|
+
if (!m)
|
|
1475
|
+
return false;
|
|
1476
|
+
const auth = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
|
|
1477
|
+
if (req.method !== "POST" || auth.length !== key.length || !crypto2.timingSafeEqual(Buffer.from(auth), Buffer.from(key)))
|
|
1478
|
+
return reply(res, 401, { error: "unauthorized" }), true;
|
|
1479
|
+
let s = "";
|
|
1480
|
+
for await (const d of req)
|
|
1481
|
+
if ((s += d).length > 8 * 1024 * 1024)
|
|
1482
|
+
return reply(res, 413), true;
|
|
1483
|
+
let msg;
|
|
1484
|
+
try {
|
|
1485
|
+
msg = JSON.parse(s);
|
|
1486
|
+
} catch {
|
|
1487
|
+
return reply(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }), true;
|
|
1488
|
+
}
|
|
1489
|
+
if (msg.id === undefined || msg.id === null)
|
|
1490
|
+
return reply(res, 202), true;
|
|
1491
|
+
const ok = (result) => reply(res, 200, { jsonrpc: "2.0", id: msg.id, result });
|
|
1492
|
+
const found = routes.get(m[2]);
|
|
1493
|
+
const target = found && found.projectId === m[1] ? found : undefined;
|
|
1494
|
+
switch (msg.method) {
|
|
1495
|
+
case "initialize":
|
|
1496
|
+
return ok({ protocolVersion: String(msg.params?.protocolVersion || "2025-06-18"), capabilities: { tools: { listChanged: false } }, serverInfo: { name: "hypeframe", title: "HypeFrame", version: VERSION }, instructions: MCP_INSTRUCTIONS }), true;
|
|
1497
|
+
case "ping":
|
|
1498
|
+
return ok({}), true;
|
|
1499
|
+
case "tools/list":
|
|
1500
|
+
return ok({ tools: target ? [...target.alat, FILE_TOOL] : [] }), true;
|
|
1501
|
+
case "tools/call": {
|
|
1502
|
+
if (!target)
|
|
1503
|
+
return o.onToolError?.("tab"), ok({ isError: true, content: [{ type: "text", text: NOT_OPEN }] }), true;
|
|
1504
|
+
if (msg.params?.name === FILE_TOOL.name)
|
|
1505
|
+
return ok(await sendFile(target, target.projectId, msg.params?.arguments)), true;
|
|
1506
|
+
const body = { nama: String(msg.params?.name ?? ""), arg: msg.params?.arguments ?? {} };
|
|
1507
|
+
if (bytes(body) > MAX_TOOL_ARGS)
|
|
1508
|
+
return ok({ isError: true, content: [{ type: "text", text: `The arguments of ${body.nama} are too large to send to HypeFrame Web (over 200 KB). Split the work into smaller steps.` }] }), true;
|
|
1509
|
+
const a = await o.conn.request(target.dari, "alat", body);
|
|
1510
|
+
if (a.ok === false) {
|
|
1511
|
+
const error = String(a.error) in ERRORS ? String(a.error) : "tab";
|
|
1512
|
+
o.onToolError?.(error);
|
|
1513
|
+
return ok({ isError: true, content: [{ type: "text", text: ERRORS[error] }] }), true;
|
|
1514
|
+
}
|
|
1515
|
+
return ok({ isError: !!a.isError, content: Array.isArray(a.content) ? a.content : [] }), true;
|
|
1516
|
+
}
|
|
1517
|
+
default:
|
|
1518
|
+
return reply(res, 200, { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `Method not found: ${msg.method}` } }), true;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
function capabilities() {
|
|
1522
|
+
return readInstalled().filter((a) => isSupported(a.id) || process.env.HYPEFRAME_ACP_REGISTRY).slice(0, 8).map((a) => ({ id: a.id, nama: a.name, siap: a.ready === true }));
|
|
1523
|
+
}
|
|
1524
|
+
return { work, route, capabilities, key, stop: () => (clearInterval(ticker), sessions.stopAll()) };
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// src/agent/mcp-bridge.ts
|
|
1528
|
+
import fs10 from "node:fs";
|
|
1529
|
+
import path7 from "node:path";
|
|
1530
|
+
import readline2 from "node:readline";
|
|
1531
|
+
|
|
1532
|
+
// src/util/runtime.ts
|
|
1533
|
+
import fs9 from "node:fs";
|
|
1534
|
+
import path6 from "node:path";
|
|
1535
|
+
function isStandalone() {
|
|
1536
|
+
return path6.basename(process.execPath).toLowerCase().startsWith("hypeframe");
|
|
1537
|
+
}
|
|
1538
|
+
function runtimeLabel() {
|
|
1539
|
+
const bun = process.versions.bun;
|
|
1540
|
+
return bun && !isStandalone() ? `Bun ${bun}` : isStandalone() ? `Bun ${bun ?? "?"} (standalone)` : `Node ${process.versions.node}`;
|
|
1541
|
+
}
|
|
1542
|
+
function launchCommand() {
|
|
1543
|
+
if (isStandalone())
|
|
1544
|
+
return [process.execPath];
|
|
1545
|
+
try {
|
|
1546
|
+
const script = fs9.realpathSync(process.argv[1] || "");
|
|
1547
|
+
return /[\\/]_npx[\\/]/.test(script) ? null : [process.execPath, script];
|
|
1548
|
+
} catch {
|
|
1549
|
+
return null;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
var INSTALL_URL = "https://hype-frame.com/install";
|
|
1553
|
+
|
|
1554
|
+
// src/agent/mcp-bridge.ts
|
|
1555
|
+
var BRIDGE_SOURCE = `// HypeFrame MCP bridge (written by hypeframe; do not edit). stdin JSON-RPC lines -> engine -> stdout.
|
|
1556
|
+
import readline from 'node:readline';
|
|
1557
|
+
const url = process.env.HF_MCP_URL, key = process.env.HF_MCP_KUNCI;
|
|
1558
|
+
if (!url || !key) { process.stderr.write('HF_MCP_URL and HF_MCP_KUNCI are required\\n'); process.exit(2); }
|
|
1559
|
+
const out = (m) => process.stdout.write(JSON.stringify(m) + '\\n');
|
|
1560
|
+
const busy = new Set();
|
|
1561
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
1562
|
+
rl.on('line', (line) => {
|
|
1563
|
+
if (!line.trim()) return;
|
|
1564
|
+
let m = null;
|
|
1565
|
+
try { m = JSON.parse(line); } catch { return out({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
|
|
1566
|
+
const p = (async () => {
|
|
1567
|
+
try {
|
|
1568
|
+
const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + key }, body: line });
|
|
1569
|
+
if (r.status === 202) return;
|
|
1570
|
+
const t = (await r.text()).trim();
|
|
1571
|
+
if (t) process.stdout.write(t + '\\n');
|
|
1572
|
+
} catch (e) {
|
|
1573
|
+
if (m && m.id !== undefined) out({ jsonrpc: '2.0', id: m.id, error: { code: -32603, message: 'HypeFrame engine is not reachable: ' + e.message } });
|
|
1574
|
+
}
|
|
1575
|
+
})();
|
|
1576
|
+
busy.add(p);
|
|
1577
|
+
p.finally(() => busy.delete(p));
|
|
1578
|
+
});
|
|
1579
|
+
rl.on('close', () => Promise.all(busy).then(() => process.exit(0)));
|
|
1580
|
+
`;
|
|
1581
|
+
function bridgeLaunch() {
|
|
1582
|
+
const file = path7.join(agentDir(), "mcp-bridge.mjs");
|
|
1583
|
+
let now = "";
|
|
1584
|
+
try {
|
|
1585
|
+
now = fs10.readFileSync(file, "utf8");
|
|
1586
|
+
} catch {}
|
|
1587
|
+
if (now !== BRIDGE_SOURCE)
|
|
1588
|
+
fs10.writeFileSync(file, BRIDGE_SOURCE);
|
|
1589
|
+
return { command: process.execPath, args: [file], env: isStandalone() ? [{ name: "BUN_BE_BUN", value: "1" }] : [] };
|
|
1590
|
+
}
|
|
1591
|
+
async function runMcpBridge() {
|
|
1592
|
+
const url = process.env.HF_MCP_URL;
|
|
1593
|
+
const key = process.env.HF_MCP_KUNCI;
|
|
1594
|
+
if (!url || !key) {
|
|
1595
|
+
process.stderr.write(`hypeframe mcp-bridge: HF_MCP_URL and HF_MCP_KUNCI are required
|
|
1596
|
+
`);
|
|
1597
|
+
process.exit(2);
|
|
1598
|
+
}
|
|
1599
|
+
const out = (m) => process.stdout.write(`${JSON.stringify(m)}
|
|
1600
|
+
`);
|
|
1601
|
+
const rl = readline2.createInterface({ input: process.stdin });
|
|
1602
|
+
const busy = new Set;
|
|
1603
|
+
rl.on("line", (line) => {
|
|
1604
|
+
if (!line.trim())
|
|
1605
|
+
return;
|
|
1606
|
+
let m = null;
|
|
1607
|
+
try {
|
|
1608
|
+
m = JSON.parse(line);
|
|
1609
|
+
} catch {
|
|
1610
|
+
return out({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
|
|
1611
|
+
}
|
|
1612
|
+
const p = (async () => {
|
|
1613
|
+
try {
|
|
1614
|
+
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key}` }, body: line });
|
|
1615
|
+
if (r.status === 202)
|
|
1616
|
+
return;
|
|
1617
|
+
const text = await r.text();
|
|
1618
|
+
if (text.trim())
|
|
1619
|
+
process.stdout.write(`${text.trim()}
|
|
1620
|
+
`);
|
|
1621
|
+
} catch (e) {
|
|
1622
|
+
if (m && m.id !== undefined)
|
|
1623
|
+
out({ jsonrpc: "2.0", id: m.id, error: { code: -32603, message: `HypeFrame engine is not reachable: ${e.message}` } });
|
|
1624
|
+
}
|
|
1625
|
+
})();
|
|
1626
|
+
busy.add(p);
|
|
1627
|
+
p.finally(() => busy.delete(p));
|
|
1628
|
+
});
|
|
1629
|
+
await new Promise((ok) => rl.on("close", ok));
|
|
1630
|
+
await Promise.all(busy);
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// src/config/lock.ts
|
|
1634
|
+
import fs11 from "node:fs";
|
|
1635
|
+
class AlreadyRunning extends Error {
|
|
1636
|
+
code = "SUDAH_JALAN";
|
|
1637
|
+
}
|
|
1638
|
+
var alive = (pid) => {
|
|
1639
|
+
try {
|
|
1640
|
+
process.kill(pid, 0);
|
|
1641
|
+
return true;
|
|
1642
|
+
} catch (e) {
|
|
1643
|
+
return e.code === "EPERM";
|
|
1644
|
+
}
|
|
1645
|
+
};
|
|
1646
|
+
function runningPid() {
|
|
1647
|
+
try {
|
|
1648
|
+
const pid = Number(fs11.readFileSync(lockFile(), "utf8"));
|
|
1649
|
+
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
|
|
1650
|
+
} catch {
|
|
1651
|
+
return null;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
function singleInstance() {
|
|
1655
|
+
const f = lockFile();
|
|
1656
|
+
for (let attempt = 0;attempt < 2; attempt++) {
|
|
1657
|
+
try {
|
|
1658
|
+
const fd = fs11.openSync(f, "wx");
|
|
1659
|
+
fs11.writeSync(fd, String(process.pid));
|
|
1660
|
+
fs11.closeSync(fd);
|
|
1661
|
+
const release = () => {
|
|
1662
|
+
try {
|
|
1663
|
+
if (fs11.readFileSync(f, "utf8") === String(process.pid))
|
|
1664
|
+
fs11.rmSync(f, { force: true });
|
|
1665
|
+
} catch {}
|
|
1666
|
+
process.off("exit", release);
|
|
1667
|
+
};
|
|
1668
|
+
process.on("exit", release);
|
|
1669
|
+
return { release };
|
|
1670
|
+
} catch (e) {
|
|
1671
|
+
if (e.code !== "EEXIST")
|
|
1672
|
+
throw e;
|
|
1673
|
+
const pid = Number(fs11.readFileSync(f, "utf8"));
|
|
1674
|
+
if (Number.isInteger(pid) && pid > 0 && alive(pid))
|
|
1675
|
+
throw new AlreadyRunning("engine already running");
|
|
1676
|
+
fs11.rmSync(f, { force: true });
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
throw new AlreadyRunning("engine already running");
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
// src/engine/connection.ts
|
|
1683
|
+
import crypto3 from "node:crypto";
|
|
1684
|
+
import { EventEmitter as EventEmitter2 } from "node:events";
|
|
636
1685
|
import WebSocket from "ws";
|
|
637
1686
|
var SILENCE_MAX_MS = 70000;
|
|
638
1687
|
|
|
639
|
-
class Connection extends
|
|
1688
|
+
class Connection extends EventEmitter2 {
|
|
640
1689
|
o;
|
|
641
1690
|
url;
|
|
642
1691
|
ws = null;
|
|
@@ -672,6 +1721,33 @@ class Connection extends EventEmitter {
|
|
|
672
1721
|
news(kind, body = {}) {
|
|
673
1722
|
this.send({ ...body, t: "kabar", jenis: kind });
|
|
674
1723
|
}
|
|
1724
|
+
nextReq = 1;
|
|
1725
|
+
waiting = new Map;
|
|
1726
|
+
request(ke, kind, body, timeoutMs = 55000) {
|
|
1727
|
+
if (!this.connected)
|
|
1728
|
+
return Promise.resolve({ ok: false, error: "terputus" });
|
|
1729
|
+
const id = `q${this.nextReq++}${crypto3.randomBytes(6).toString("hex")}`;
|
|
1730
|
+
return new Promise((ok) => {
|
|
1731
|
+
const timer = setTimeout(() => (this.waiting.delete(id), ok({ ok: false, error: "waktu" })), timeoutMs);
|
|
1732
|
+
timer.unref?.();
|
|
1733
|
+
this.waiting.set(id, { ok, timer });
|
|
1734
|
+
this.send({ ...body, t: "minta", ke, id, jenis: kind });
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
answer(m) {
|
|
1738
|
+
const w = this.waiting.get(String(m.id));
|
|
1739
|
+
if (!w)
|
|
1740
|
+
return;
|
|
1741
|
+
clearTimeout(w.timer);
|
|
1742
|
+
this.waiting.delete(String(m.id));
|
|
1743
|
+
const { t: _t, id: _id, dari: _dari, ...rest } = m;
|
|
1744
|
+
w.ok(rest);
|
|
1745
|
+
}
|
|
1746
|
+
dropWaiting() {
|
|
1747
|
+
for (const w of this.waiting.values())
|
|
1748
|
+
clearTimeout(w.timer), w.ok({ ok: false, error: "terputus" });
|
|
1749
|
+
this.waiting.clear();
|
|
1750
|
+
}
|
|
675
1751
|
get connected() {
|
|
676
1752
|
return this.ws?.readyState === WebSocket.OPEN && !!this.id;
|
|
677
1753
|
}
|
|
@@ -710,6 +1786,8 @@ class Connection extends EventEmitter {
|
|
|
710
1786
|
const result = await this.o.handler(m);
|
|
711
1787
|
if (ws === this.ws)
|
|
712
1788
|
this.send({ t: "balas", ke: m.dari, id: m.id, ...result });
|
|
1789
|
+
} else if (m.t === "jawab") {
|
|
1790
|
+
this.answer(m);
|
|
713
1791
|
}
|
|
714
1792
|
});
|
|
715
1793
|
ws.on("error", () => {
|
|
@@ -720,6 +1798,7 @@ class Connection extends EventEmitter {
|
|
|
720
1798
|
if (ws !== this.ws)
|
|
721
1799
|
return;
|
|
722
1800
|
this.id = null;
|
|
1801
|
+
this.dropWaiting();
|
|
723
1802
|
if (code === CloseCode.TokenRevoked) {
|
|
724
1803
|
deleteAccount();
|
|
725
1804
|
this.running = false;
|
|
@@ -738,21 +1817,22 @@ class Connection extends EventEmitter {
|
|
|
738
1817
|
}
|
|
739
1818
|
}
|
|
740
1819
|
|
|
741
|
-
//
|
|
1820
|
+
// src/engine/handler.ts
|
|
742
1821
|
function createHandler(work) {
|
|
743
1822
|
return async function handle(c) {
|
|
744
1823
|
const kind = String(c?.jenis || "");
|
|
745
|
-
|
|
1824
|
+
const fn = ALLOWED_KINDS.includes(kind) ? work[kind] : undefined;
|
|
1825
|
+
if (!fn)
|
|
746
1826
|
return { ok: false, error: "jenis" };
|
|
747
1827
|
try {
|
|
748
|
-
return { ok: true, ...await
|
|
1828
|
+
return { ok: true, ...await fn(c) };
|
|
749
1829
|
} catch (e) {
|
|
750
1830
|
return { ok: false, error: "galat", pesan: String(e?.message || e).slice(0, 200) };
|
|
751
1831
|
}
|
|
752
1832
|
};
|
|
753
1833
|
}
|
|
754
1834
|
|
|
755
|
-
//
|
|
1835
|
+
// src/engine/pairing.ts
|
|
756
1836
|
var sleep = (ms, signal) => new Promise((ok, fail) => {
|
|
757
1837
|
const timer = setTimeout(ok, ms);
|
|
758
1838
|
signal?.addEventListener("abort", () => (clearTimeout(timer), fail(new Error("Dibatalkan."))), { once: true });
|
|
@@ -828,55 +1908,74 @@ async function pair(o) {
|
|
|
828
1908
|
}
|
|
829
1909
|
}
|
|
830
1910
|
|
|
831
|
-
//
|
|
832
|
-
import
|
|
833
|
-
import fs6 from "node:fs";
|
|
1911
|
+
// src/render/chrome.ts
|
|
1912
|
+
import fs13 from "node:fs";
|
|
834
1913
|
import http from "node:http";
|
|
835
|
-
import
|
|
1914
|
+
import path9 from "node:path";
|
|
836
1915
|
import { Browser, detectBrowserPlatform, getInstalledBrowsers, install, resolveBuildId } from "@puppeteer/browsers";
|
|
837
1916
|
import puppeteer from "puppeteer-core";
|
|
1917
|
+
|
|
1918
|
+
// src/util/which.ts
|
|
1919
|
+
import fs12 from "node:fs";
|
|
1920
|
+
import path8 from "node:path";
|
|
1921
|
+
function isAndroid() {
|
|
1922
|
+
return process.platform === "android" || !!process.env.TERMUX_VERSION || (process.env.PREFIX ?? "").includes("/com.termux/");
|
|
1923
|
+
}
|
|
1924
|
+
function onPath(name) {
|
|
1925
|
+
if (!/^[\w.@+-]{1,80}$/.test(name))
|
|
1926
|
+
return null;
|
|
1927
|
+
const file = process.platform === "win32" ? /\.exe$/i.test(name) ? name : `${name}.exe` : name;
|
|
1928
|
+
for (const dir of (process.env.PATH || "").split(path8.delimiter).filter(Boolean)) {
|
|
1929
|
+
const f = path8.join(dir, file);
|
|
1930
|
+
try {
|
|
1931
|
+
const st = fs12.statSync(f);
|
|
1932
|
+
if (st.isFile() && (process.platform === "win32" || st.mode & 73))
|
|
1933
|
+
return f;
|
|
1934
|
+
} catch {}
|
|
1935
|
+
}
|
|
1936
|
+
return null;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
// src/render/chrome.ts
|
|
1940
|
+
function chromePlatformArgs(android = isAndroid()) {
|
|
1941
|
+
return android ? ["--no-sandbox"] : [];
|
|
1942
|
+
}
|
|
838
1943
|
function candidates() {
|
|
839
1944
|
const e = process.env;
|
|
840
1945
|
if (process.platform === "win32") {
|
|
841
|
-
return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [
|
|
1946
|
+
return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [path9.join(d, "Google", "Chrome", "Application", "chrome.exe"), path9.join(d, "Microsoft", "Edge", "Application", "msedge.exe")]);
|
|
842
1947
|
}
|
|
843
1948
|
if (process.platform === "darwin") {
|
|
844
1949
|
return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
|
|
845
1950
|
}
|
|
846
|
-
|
|
847
|
-
for (const n of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) {
|
|
848
|
-
try {
|
|
849
|
-
const p = execFileSync("which", [n], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
850
|
-
if (p)
|
|
851
|
-
found.push(p);
|
|
852
|
-
} catch {}
|
|
853
|
-
}
|
|
854
|
-
return found;
|
|
1951
|
+
return ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"].map((n) => onPath(n)).filter((p) => !!p);
|
|
855
1952
|
}
|
|
856
1953
|
function findChrome() {
|
|
857
1954
|
const forced = process.env.HYPEFRAME_CHROME;
|
|
858
1955
|
if (forced)
|
|
859
|
-
return
|
|
860
|
-
return candidates().find((p) =>
|
|
1956
|
+
return fs13.existsSync(forced) ? forced : null;
|
|
1957
|
+
return candidates().find((p) => fs13.existsSync(p)) || null;
|
|
861
1958
|
}
|
|
862
1959
|
async function cachedChrome(cacheDir) {
|
|
863
1960
|
try {
|
|
864
|
-
const all = await getInstalledBrowsers({ cacheDir:
|
|
865
|
-
return all.find((b) => b.browser === Browser.CHROME &&
|
|
1961
|
+
const all = await getInstalledBrowsers({ cacheDir: path9.join(cacheDir, "chrome") });
|
|
1962
|
+
return all.find((b) => b.browser === Browser.CHROME && fs13.existsSync(b.executablePath))?.executablePath ?? null;
|
|
866
1963
|
} catch {
|
|
867
1964
|
return null;
|
|
868
1965
|
}
|
|
869
1966
|
}
|
|
870
1967
|
async function prepareChrome(cacheDir, progress = () => {
|
|
871
1968
|
return;
|
|
872
|
-
}) {
|
|
1969
|
+
}, opts = {}) {
|
|
873
1970
|
const found = findChrome();
|
|
874
1971
|
if (found)
|
|
875
1972
|
return found;
|
|
1973
|
+
if (opts.android ?? isAndroid())
|
|
1974
|
+
throw new Error("Chromium belum terpasang. Di Termux jalankan: pkg install x11-repo && pkg install chromium");
|
|
876
1975
|
const platform = detectBrowserPlatform();
|
|
877
1976
|
if (!platform)
|
|
878
1977
|
throw new Error("Sistem ini belum didukung untuk render (Chrome tidak tersedia).");
|
|
879
|
-
const dir =
|
|
1978
|
+
const dir = path9.join(cacheDir, "chrome");
|
|
880
1979
|
const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
|
|
881
1980
|
progress(0, `Chrome ${buildId}`);
|
|
882
1981
|
const r = await install({
|
|
@@ -907,7 +2006,7 @@ var TRY_ENCODER = `async (c) => {
|
|
|
907
2006
|
async function checkChrome(chrome, { gpu = false } = {}) {
|
|
908
2007
|
const srv = http.createServer((_q, r) => (r.writeHead(200, { "content-type": "text/html" }), r.end("<!doctype html><title>check</title>")));
|
|
909
2008
|
await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
|
|
910
|
-
const b = await puppeteer.launch({ executablePath: chrome, headless: true, protocolTimeout: 60000, args: ["--no-first-run", "--disable-extensions", ...gpu ? [] : softwareGpuArgs] });
|
|
2009
|
+
const b = await puppeteer.launch({ executablePath: chrome, headless: true, protocolTimeout: 60000, args: ["--no-first-run", "--disable-extensions", ...gpu ? [] : softwareGpuArgs, ...chromePlatformArgs()] });
|
|
911
2010
|
try {
|
|
912
2011
|
const p = await b.newPage();
|
|
913
2012
|
await p.goto(`http://127.0.0.1:${srv.address().port}/`);
|
|
@@ -925,11 +2024,11 @@ async function checkChrome(chrome, { gpu = false } = {}) {
|
|
|
925
2024
|
}
|
|
926
2025
|
}
|
|
927
2026
|
|
|
928
|
-
//
|
|
929
|
-
import
|
|
930
|
-
import
|
|
2027
|
+
// src/render/ffmpeg.ts
|
|
2028
|
+
import crypto4 from "node:crypto";
|
|
2029
|
+
import fs14 from "node:fs";
|
|
931
2030
|
import fsp from "node:fs/promises";
|
|
932
|
-
import
|
|
2031
|
+
import path10 from "node:path";
|
|
933
2032
|
import { pipeline } from "node:stream/promises";
|
|
934
2033
|
import { Readable } from "node:stream";
|
|
935
2034
|
import zlib from "node:zlib";
|
|
@@ -943,19 +2042,22 @@ var FFMPEG_PINNED = {
|
|
|
943
2042
|
"darwin-arm64": { sha256: "6be74d6f449889c2e87a75873894f8520cad56c08ac76f2a628d85b0519daaca", size: 19253088 }
|
|
944
2043
|
};
|
|
945
2044
|
var exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
|
|
946
|
-
var cached2 = (cacheDir) =>
|
|
947
|
-
|
|
2045
|
+
var cached2 = (cacheDir) => path10.join(cacheDir, "ffmpeg", FFMPEG_RELEASE, exe);
|
|
2046
|
+
var thisPlatform = () => `${process.platform}-${process.arch}`;
|
|
2047
|
+
async function findFfmpeg(cacheDir, key = thisPlatform()) {
|
|
948
2048
|
const forced = process.env.HYPEFRAME_FFMPEG;
|
|
949
2049
|
if (forced)
|
|
950
|
-
return
|
|
2050
|
+
return fs14.existsSync(forced) ? forced : null;
|
|
2051
|
+
if (!FFMPEG_PINNED[key])
|
|
2052
|
+
return onPath("ffmpeg");
|
|
951
2053
|
try {
|
|
952
2054
|
const mod = await import("ffmpeg-static");
|
|
953
2055
|
const p = typeof mod.default === "string" ? mod.default : null;
|
|
954
|
-
if (p &&
|
|
2056
|
+
if (p && fs14.existsSync(p))
|
|
955
2057
|
return p;
|
|
956
2058
|
} catch {}
|
|
957
2059
|
const c = cached2(cacheDir);
|
|
958
|
-
return
|
|
2060
|
+
return fs14.existsSync(c) ? c : null;
|
|
959
2061
|
}
|
|
960
2062
|
async function downloadVerified(url, sha256, dest, progress = () => {
|
|
961
2063
|
return;
|
|
@@ -964,9 +2066,9 @@ async function downloadVerified(url, sha256, dest, progress = () => {
|
|
|
964
2066
|
if (!r.ok || !r.body)
|
|
965
2067
|
throw new Error(`download ${r.status}`);
|
|
966
2068
|
const total = Number(r.headers.get("content-length")) || 0;
|
|
967
|
-
await fsp.mkdir(
|
|
2069
|
+
await fsp.mkdir(path10.dirname(dest), { recursive: true });
|
|
968
2070
|
const tmp = `${dest}.download`;
|
|
969
|
-
const hash =
|
|
2071
|
+
const hash = crypto4.createHash("sha256");
|
|
970
2072
|
let got = 0;
|
|
971
2073
|
let last = -10;
|
|
972
2074
|
const body = Readable.fromWeb(r.body).on("data", (c) => {
|
|
@@ -976,13 +2078,13 @@ async function downloadVerified(url, sha256, dest, progress = () => {
|
|
|
976
2078
|
if (pct - last >= 10)
|
|
977
2079
|
last = pct, progress(pct);
|
|
978
2080
|
});
|
|
979
|
-
await pipeline(body,
|
|
2081
|
+
await pipeline(body, fs14.createWriteStream(tmp));
|
|
980
2082
|
if (hash.digest("hex") !== sha256) {
|
|
981
2083
|
await fsp.rm(tmp, { force: true });
|
|
982
2084
|
throw new Error("ffmpeg: sidik unduhan tidak cocok, berkas ditolak.");
|
|
983
2085
|
}
|
|
984
2086
|
if (gunzip) {
|
|
985
|
-
await pipeline(
|
|
2087
|
+
await pipeline(fs14.createReadStream(tmp), zlib.createGunzip(), fs14.createWriteStream(`${tmp}.raw`));
|
|
986
2088
|
await fsp.rm(tmp, { force: true });
|
|
987
2089
|
await fsp.rename(`${tmp}.raw`, dest);
|
|
988
2090
|
} else
|
|
@@ -992,30 +2094,29 @@ async function downloadVerified(url, sha256, dest, progress = () => {
|
|
|
992
2094
|
}
|
|
993
2095
|
async function prepareFfmpeg(cacheDir, progress = () => {
|
|
994
2096
|
return;
|
|
995
|
-
}) {
|
|
996
|
-
const found = await findFfmpeg(cacheDir);
|
|
2097
|
+
}, key = thisPlatform()) {
|
|
2098
|
+
const found = await findFfmpeg(cacheDir, key);
|
|
997
2099
|
if (found)
|
|
998
2100
|
return found;
|
|
999
|
-
const key = `${process.platform}-${process.arch}`;
|
|
1000
2101
|
const pin = FFMPEG_PINNED[key];
|
|
1001
2102
|
if (!pin)
|
|
1002
|
-
throw new Error(`ffmpeg tidak tersedia untuk ${key}`);
|
|
2103
|
+
throw new Error(key.startsWith("android") ? "ffmpeg belum terpasang. Di Termux jalankan: pkg install ffmpeg" : `ffmpeg tidak tersedia untuk ${key}`);
|
|
1003
2104
|
progress(0);
|
|
1004
2105
|
await downloadVerified(`${BASE}ffmpeg-${key}.gz`, pin.sha256, cached2(cacheDir), progress, true);
|
|
1005
2106
|
return cached2(cacheDir);
|
|
1006
2107
|
}
|
|
1007
2108
|
|
|
1008
|
-
//
|
|
1009
|
-
import { spawn } from "node:child_process";
|
|
1010
|
-
import
|
|
1011
|
-
import
|
|
2109
|
+
// src/render/job.ts
|
|
2110
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2111
|
+
import crypto5 from "node:crypto";
|
|
2112
|
+
import fs15 from "node:fs";
|
|
1012
2113
|
import fsp2 from "node:fs/promises";
|
|
1013
|
-
import
|
|
2114
|
+
import path11 from "node:path";
|
|
1014
2115
|
import puppeteer2 from "puppeteer-core";
|
|
1015
2116
|
var LIMIT_SECONDS = 1800;
|
|
1016
2117
|
function run(cmd, args, limitSeconds = 600) {
|
|
1017
2118
|
return new Promise((ok, fail) => {
|
|
1018
|
-
const p =
|
|
2119
|
+
const p = spawn2(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
1019
2120
|
let err = "";
|
|
1020
2121
|
p.stderr.on("data", (d) => err = (err + d).slice(-2000));
|
|
1021
2122
|
const timer = setTimeout(() => p.kill("SIGKILL"), limitSeconds * 1000);
|
|
@@ -1027,7 +2128,7 @@ function run(cmd, args, limitSeconds = 600) {
|
|
|
1027
2128
|
function saveBody(req, to, max) {
|
|
1028
2129
|
return new Promise((ok, fail) => {
|
|
1029
2130
|
let n = 0;
|
|
1030
|
-
const out =
|
|
2131
|
+
const out = fs15.createWriteStream(to);
|
|
1031
2132
|
req.on("data", (d) => {
|
|
1032
2133
|
n += d.length;
|
|
1033
2134
|
if (n > max)
|
|
@@ -1058,7 +2159,7 @@ function createJobRunner(o) {
|
|
|
1058
2159
|
const renderer = async (task, { progress, signal }) => {
|
|
1059
2160
|
if (task.kind === "klip" && task.transparent && !transparent)
|
|
1060
2161
|
throw new Error(EngineError.NoTransparent);
|
|
1061
|
-
const key =
|
|
2162
|
+
const key = crypto5.randomBytes(16).toString("hex");
|
|
1062
2163
|
let finish;
|
|
1063
2164
|
const finished = new Promise((ok) => finish = ok);
|
|
1064
2165
|
running.set(task.job, { key, task, progress, finish });
|
|
@@ -1069,9 +2170,9 @@ function createJobRunner(o) {
|
|
|
1069
2170
|
let browser;
|
|
1070
2171
|
try {
|
|
1071
2172
|
progress(0, "Menyiapkan");
|
|
1072
|
-
const profile =
|
|
1073
|
-
await fsp2.mkdir(
|
|
1074
|
-
await fsp2.writeFile(
|
|
2173
|
+
const profile = path11.join(task.dir, "profil");
|
|
2174
|
+
await fsp2.mkdir(path11.join(profile, "Default"), { recursive: true });
|
|
2175
|
+
await fsp2.writeFile(path11.join(profile, "Default", "Preferences"), JSON.stringify({ webkit: { webprefs: { fonts: { standard: { Zyyy: "Roboto" }, sansserif: { Zyyy: "Roboto" }, serif: { Zyyy: "Noto Serif" } } } } }));
|
|
1075
2176
|
browser = await puppeteer2.launch({
|
|
1076
2177
|
executablePath: chrome,
|
|
1077
2178
|
headless: true,
|
|
@@ -1089,7 +2190,8 @@ function createJobRunner(o) {
|
|
|
1089
2190
|
"--enable-unsafe-webgpu",
|
|
1090
2191
|
...gpu ? [] : ["--use-webgpu-adapter=swiftshader"],
|
|
1091
2192
|
"--enable-features=Vulkan",
|
|
1092
|
-
"--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1"
|
|
2193
|
+
"--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1",
|
|
2194
|
+
...chromePlatformArgs()
|
|
1093
2195
|
]
|
|
1094
2196
|
});
|
|
1095
2197
|
browser.on("disconnected", () => finish({ error: EngineError.ChromeStopped }));
|
|
@@ -1101,9 +2203,9 @@ function createJobRunner(o) {
|
|
|
1101
2203
|
if (result.error)
|
|
1102
2204
|
throw new Error(result.error);
|
|
1103
2205
|
progress(99, clip ? "Menyelesaikan klip" : "Menyelesaikan video");
|
|
1104
|
-
const raw =
|
|
2206
|
+
const raw = path11.join(task.dir, "mentah.mp4");
|
|
1105
2207
|
const webm = clip && task.transparent;
|
|
1106
|
-
const file =
|
|
2208
|
+
const file = path11.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
|
|
1107
2209
|
if (clip)
|
|
1108
2210
|
await fsp2.rename(raw, file);
|
|
1109
2211
|
else
|
|
@@ -1130,11 +2232,11 @@ function createJobRunner(o) {
|
|
|
1130
2232
|
return res.writeHead(403), res.end(), true;
|
|
1131
2233
|
const pkg = r.task.packageDir;
|
|
1132
2234
|
if (m[2] === "proyek.json" || m[2] === "klip.json" || m[3]) {
|
|
1133
|
-
const f = m[3] ?
|
|
1134
|
-
if (!
|
|
2235
|
+
const f = m[3] ? path11.join(pkg, "aset", m[3]) : path11.join(pkg, m[2]);
|
|
2236
|
+
if (!fs15.existsSync(f))
|
|
1135
2237
|
return res.writeHead(404), res.end(), true;
|
|
1136
2238
|
res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp2.stat(f)).size });
|
|
1137
|
-
|
|
2239
|
+
fs15.createReadStream(f).pipe(res);
|
|
1138
2240
|
return true;
|
|
1139
2241
|
}
|
|
1140
2242
|
if (m[2] === "kemajuan") {
|
|
@@ -1151,7 +2253,7 @@ function createJobRunner(o) {
|
|
|
1151
2253
|
r.finish({ error: String(b.pesan || "Render gagal.").slice(0, 300) });
|
|
1152
2254
|
return res.writeHead(204), res.end(), true;
|
|
1153
2255
|
}
|
|
1154
|
-
await saveBody(req,
|
|
2256
|
+
await saveBody(req, path11.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
|
|
1155
2257
|
r.finish({ audio: String(req.headers["x-kodek-audio"] || "") });
|
|
1156
2258
|
res.writeHead(204);
|
|
1157
2259
|
res.end();
|
|
@@ -1160,10 +2262,10 @@ function createJobRunner(o) {
|
|
|
1160
2262
|
return { renderer, route, setPort: (p) => void (port = p) };
|
|
1161
2263
|
}
|
|
1162
2264
|
|
|
1163
|
-
//
|
|
1164
|
-
import
|
|
2265
|
+
// src/render/page.ts
|
|
2266
|
+
import fs16 from "node:fs";
|
|
1165
2267
|
import fsp3 from "node:fs/promises";
|
|
1166
|
-
import
|
|
2268
|
+
import path12 from "node:path";
|
|
1167
2269
|
var TYPES = {
|
|
1168
2270
|
".html": "text/html; charset=utf-8",
|
|
1169
2271
|
".js": "text/javascript",
|
|
@@ -1184,13 +2286,13 @@ var SAFE_PATH = /^[\w@.+-]+(?:\/[\w@.+-]+)*$/;
|
|
|
1184
2286
|
var VERSION_ID = /^[0-9a-f]{12}$/;
|
|
1185
2287
|
function createPage({ web, cacheDir }) {
|
|
1186
2288
|
const base = `${String(web || "").replace(/\/+$/, "")}/render/`;
|
|
1187
|
-
const root =
|
|
2289
|
+
const root = path12.join(cacheDir, "halaman");
|
|
1188
2290
|
let version = null;
|
|
1189
|
-
const versionDir = () =>
|
|
2291
|
+
const versionDir = () => path12.join(root, version);
|
|
1190
2292
|
const pending = new Map;
|
|
1191
2293
|
async function download(rel) {
|
|
1192
|
-
const target =
|
|
1193
|
-
if (
|
|
2294
|
+
const target = path12.join(versionDir(), rel);
|
|
2295
|
+
if (fs16.existsSync(target))
|
|
1194
2296
|
return target;
|
|
1195
2297
|
if (!pending.has(rel)) {
|
|
1196
2298
|
pending.set(rel, (async () => {
|
|
@@ -1198,7 +2300,7 @@ function createPage({ web, cacheDir }) {
|
|
|
1198
2300
|
if (!r.ok)
|
|
1199
2301
|
throw Object.assign(new Error(`halaman ${rel}: ${r.status}`), { status: r.status });
|
|
1200
2302
|
const body = Buffer.from(await r.arrayBuffer());
|
|
1201
|
-
await fsp3.mkdir(
|
|
2303
|
+
await fsp3.mkdir(path12.dirname(target), { recursive: true });
|
|
1202
2304
|
await fsp3.writeFile(`${target}.tmp`, body);
|
|
1203
2305
|
await fsp3.rename(`${target}.tmp`, target);
|
|
1204
2306
|
return target;
|
|
@@ -1222,10 +2324,10 @@ function createPage({ web, cacheDir }) {
|
|
|
1222
2324
|
await download(f);
|
|
1223
2325
|
if (old !== version) {
|
|
1224
2326
|
const all = (await fsp3.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
|
|
1225
|
-
const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(
|
|
2327
|
+
const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(path12.join(root, d))).mtimeMs })));
|
|
1226
2328
|
for (const { d } of dated.sort((a, b) => b.t - a.t).slice(2))
|
|
1227
2329
|
if (d !== version)
|
|
1228
|
-
await fsp3.rm(
|
|
2330
|
+
await fsp3.rm(path12.join(root, d), { recursive: true, force: true });
|
|
1229
2331
|
}
|
|
1230
2332
|
return { version };
|
|
1231
2333
|
}
|
|
@@ -1242,8 +2344,8 @@ function createPage({ web, cacheDir }) {
|
|
|
1242
2344
|
return res.writeHead(404), res.end(), true;
|
|
1243
2345
|
try {
|
|
1244
2346
|
const f = await download(rel);
|
|
1245
|
-
res.writeHead(200, { "content-type": TYPES[
|
|
1246
|
-
|
|
2347
|
+
res.writeHead(200, { "content-type": TYPES[path12.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
|
|
2348
|
+
fs16.createReadStream(f).pipe(res);
|
|
1247
2349
|
} catch (e) {
|
|
1248
2350
|
res.writeHead(e.status === 404 ? 404 : 502);
|
|
1249
2351
|
res.end();
|
|
@@ -1259,15 +2361,15 @@ function createPage({ web, cacheDir }) {
|
|
|
1259
2361
|
};
|
|
1260
2362
|
}
|
|
1261
2363
|
|
|
1262
|
-
//
|
|
1263
|
-
import
|
|
1264
|
-
import
|
|
2364
|
+
// src/render/service.ts
|
|
2365
|
+
import crypto6 from "node:crypto";
|
|
2366
|
+
import fs17 from "node:fs";
|
|
1265
2367
|
import fsp4 from "node:fs/promises";
|
|
1266
2368
|
import http2 from "node:http";
|
|
1267
|
-
import
|
|
2369
|
+
import path13 from "node:path";
|
|
1268
2370
|
import yauzl from "yauzl";
|
|
1269
2371
|
var ACTIVE = new Set(["unggah", "antre", "jalan"]);
|
|
1270
|
-
var safeEqual = (a, b) => a.length === b.length &&
|
|
2372
|
+
var safeEqual = (a, b) => a.length === b.length && crypto6.timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
1271
2373
|
var BAD_ENTRY = /relative path|absolute path|invalid characters/i;
|
|
1272
2374
|
function listZip(f) {
|
|
1273
2375
|
return new Promise((ok, fail) => {
|
|
@@ -1291,14 +2393,14 @@ function extractZip(f, to) {
|
|
|
1291
2393
|
zip.on("entry", (en) => {
|
|
1292
2394
|
if (en.fileName.endsWith("/"))
|
|
1293
2395
|
return zip.readEntry();
|
|
1294
|
-
const target =
|
|
1295
|
-
if (!target.startsWith(to +
|
|
2396
|
+
const target = path13.join(to, en.fileName);
|
|
2397
|
+
if (!target.startsWith(to + path13.sep))
|
|
1296
2398
|
return fail(new Error(EngineError.BadPackage));
|
|
1297
|
-
|
|
2399
|
+
fs17.mkdirSync(path13.dirname(target), { recursive: true });
|
|
1298
2400
|
zip.openReadStream(en, (e2, s) => {
|
|
1299
2401
|
if (e2 || !s)
|
|
1300
2402
|
return fail(e2 ?? new Error("zip"));
|
|
1301
|
-
const out =
|
|
2403
|
+
const out = fs17.createWriteStream(target);
|
|
1302
2404
|
s.pipe(out);
|
|
1303
2405
|
out.on("finish", () => zip.readEntry());
|
|
1304
2406
|
out.on("error", fail);
|
|
@@ -1313,13 +2415,13 @@ function extractZip(f, to) {
|
|
|
1313
2415
|
function saveBody2(req, to, max) {
|
|
1314
2416
|
return new Promise((ok, fail) => {
|
|
1315
2417
|
let n = 0;
|
|
1316
|
-
const out =
|
|
2418
|
+
const out = fs17.createWriteStream(to);
|
|
1317
2419
|
req.on("data", (d) => {
|
|
1318
2420
|
n += d.length;
|
|
1319
2421
|
if (n > max) {
|
|
1320
2422
|
req.destroy();
|
|
1321
2423
|
out.destroy();
|
|
1322
|
-
|
|
2424
|
+
fs17.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
|
|
1323
2425
|
}
|
|
1324
2426
|
});
|
|
1325
2427
|
req.pipe(out);
|
|
@@ -1347,8 +2449,8 @@ async function createRenderService(o) {
|
|
|
1347
2449
|
return;
|
|
1348
2450
|
} } = o;
|
|
1349
2451
|
const origins = new Set([].concat(o.origin || []));
|
|
1350
|
-
const sign = (kind, body) =>
|
|
1351
|
-
const dir = (job) =>
|
|
2452
|
+
const sign = (kind, body) => crypto6.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
|
|
2453
|
+
const dir = (job) => path13.join(folder, job);
|
|
1352
2454
|
await fsp4.mkdir(folder, { recursive: true });
|
|
1353
2455
|
function readTicket(req) {
|
|
1354
2456
|
const tk = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
|
|
@@ -1370,7 +2472,7 @@ async function createRenderService(o) {
|
|
|
1370
2472
|
const jobs = new Map;
|
|
1371
2473
|
const queue = [];
|
|
1372
2474
|
let current = null;
|
|
1373
|
-
const persist = (t) => fsp4.writeFile(
|
|
2475
|
+
const persist = (t) => fsp4.writeFile(path13.join(dir(t.job), "status.json"), JSON.stringify(t)).catch(() => {
|
|
1374
2476
|
return;
|
|
1375
2477
|
});
|
|
1376
2478
|
const update = (t, patch) => (Object.assign(t, patch, { diperbarui: Date.now() }), void persist(t));
|
|
@@ -1389,19 +2491,19 @@ async function createRenderService(o) {
|
|
|
1389
2491
|
});
|
|
1390
2492
|
async function clearFiles(t, all = false) {
|
|
1391
2493
|
for (const n of all ? ["."] : ["paket", "paket.zip", "profil", "mentah.mp4", "mentah.webm"])
|
|
1392
|
-
await fsp4.rm(
|
|
2494
|
+
await fsp4.rm(path13.join(dir(t.job), n), { recursive: true, force: true }).catch(() => {
|
|
1393
2495
|
return;
|
|
1394
2496
|
});
|
|
1395
2497
|
if (!all) {
|
|
1396
2498
|
for (const f of await fsp4.readdir(dir(t.job)).catch(() => []))
|
|
1397
2499
|
if (/^p\d+$/.test(f))
|
|
1398
|
-
await fsp4.rm(
|
|
2500
|
+
await fsp4.rm(path13.join(dir(t.job), f), { force: true });
|
|
1399
2501
|
}
|
|
1400
2502
|
}
|
|
1401
2503
|
async function openPackage(t) {
|
|
1402
2504
|
const d = dir(t.job);
|
|
1403
2505
|
const main = t.tiket.jenis === "klip" ? "klip.json" : "proyek.json";
|
|
1404
|
-
const entries = await listZip(
|
|
2506
|
+
const entries = await listZip(path13.join(d, "paket.zip"));
|
|
1405
2507
|
const names = entries.map((x) => x.name).filter((n) => !n.endsWith("/"));
|
|
1406
2508
|
if (names.some((n) => n.startsWith("/") || n.includes("..") || n.includes("\\") || n !== main && !/^aset\/[\w-]+$/.test(n)))
|
|
1407
2509
|
throw new Error(EngineError.BadPackage);
|
|
@@ -1409,10 +2511,10 @@ async function createRenderService(o) {
|
|
|
1409
2511
|
throw new Error(`Paket tidak berisi ${main}.`);
|
|
1410
2512
|
if (entries.reduce((a, x) => a + x.size, 0) > maxUnzippedMb * 1048576)
|
|
1411
2513
|
throw new Error("Isi paket terlalu besar.");
|
|
1412
|
-
await extractZip(
|
|
1413
|
-
await fsp4.rm(
|
|
1414
|
-
const j = JSON.parse(await fsp4.readFile(
|
|
1415
|
-
const has = (id) => /^[\w-]+$/.test(id) &&
|
|
2514
|
+
await extractZip(path13.join(d, "paket.zip"), path13.join(d, "paket"));
|
|
2515
|
+
await fsp4.rm(path13.join(d, "paket.zip"), { force: true });
|
|
2516
|
+
const j = JSON.parse(await fsp4.readFile(path13.join(d, "paket", main), "utf8"));
|
|
2517
|
+
const has = (id) => /^[\w-]+$/.test(id) && fs17.existsSync(path13.join(d, "paket", "aset", id));
|
|
1416
2518
|
if (main === "klip.json") {
|
|
1417
2519
|
const k = j.klip || {};
|
|
1418
2520
|
const seconds = Number(k.durationInFrames) / Number(k.fps);
|
|
@@ -1460,7 +2562,7 @@ async function createRenderService(o) {
|
|
|
1460
2562
|
job: t.job,
|
|
1461
2563
|
kind: t.tiket.jenis,
|
|
1462
2564
|
dir: dir(t.job),
|
|
1463
|
-
packageDir:
|
|
2565
|
+
packageDir: path13.join(dir(t.job), "paket"),
|
|
1464
2566
|
transparent: !!t.transparan,
|
|
1465
2567
|
persen: t.persen,
|
|
1466
2568
|
width: t.tiket.w,
|
|
@@ -1480,7 +2582,7 @@ async function createRenderService(o) {
|
|
|
1480
2582
|
const size = (await fsp4.stat(h.file)).size;
|
|
1481
2583
|
if (size < 200)
|
|
1482
2584
|
throw new Error(EngineError.EmptyResult);
|
|
1483
|
-
update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas:
|
|
2585
|
+
update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path13.basename(h.file), hasilJenis: h.type });
|
|
1484
2586
|
onJob("done", t);
|
|
1485
2587
|
} catch (e) {
|
|
1486
2588
|
if (t.status !== "batal") {
|
|
@@ -1518,10 +2620,10 @@ async function createRenderService(o) {
|
|
|
1518
2620
|
if (a > z)
|
|
1519
2621
|
return res.writeHead(416, { ...h, "content-range": `bytes */${st.size}` }), res.end();
|
|
1520
2622
|
res.writeHead(206, { ...h, "content-length": z - a + 1, "content-range": `bytes ${a}-${z}/${st.size}` });
|
|
1521
|
-
return void
|
|
2623
|
+
return void fs17.createReadStream(f, { start: a, end: z }).pipe(res);
|
|
1522
2624
|
}
|
|
1523
2625
|
res.writeHead(200, { ...h, "content-length": st.size });
|
|
1524
|
-
|
|
2626
|
+
fs17.createReadStream(f).pipe(res);
|
|
1525
2627
|
}
|
|
1526
2628
|
const ROUTE = /^\/tugas(?:\/(r_[a-f0-9]{16})(\/potongan\/(\d{1,4})|\/mulai|\/hasil)?)?$/;
|
|
1527
2629
|
const server = http2.createServer(async (req, res) => {
|
|
@@ -1560,13 +2662,13 @@ async function createRenderService(o) {
|
|
|
1560
2662
|
if (t.status !== "unggah")
|
|
1561
2663
|
return json(req, res, 409, { galat: "Unggahan sudah ditutup." });
|
|
1562
2664
|
const n = Number(m[3]);
|
|
1563
|
-
const f =
|
|
1564
|
-
const before =
|
|
2665
|
+
const f = path13.join(dir(job), `p${n}`);
|
|
2666
|
+
const before = fs17.existsSync(f) ? (await fsp4.stat(f)).size : 0;
|
|
1565
2667
|
const room = Number(ticket.maksMb) * 1048576 - (t.terunggah - before);
|
|
1566
2668
|
const size = await saveBody2(req, f, Math.min(partMb * 1048576 + 1024, room));
|
|
1567
2669
|
const expected = String(req.headers["x-sha256"] || "").toLowerCase();
|
|
1568
2670
|
if (expected) {
|
|
1569
|
-
const digest =
|
|
2671
|
+
const digest = crypto6.createHash("sha256").update(await fsp4.readFile(f)).digest("hex");
|
|
1570
2672
|
if (digest !== expected) {
|
|
1571
2673
|
await fsp4.rm(f, { force: true });
|
|
1572
2674
|
update(t, { terunggah: t.terunggah - before });
|
|
@@ -1583,13 +2685,13 @@ async function createRenderService(o) {
|
|
|
1583
2685
|
const count = Number(b.jumlah);
|
|
1584
2686
|
if (!(count > 0 && count < 1e4))
|
|
1585
2687
|
return json(req, res, 400, { galat: "Jumlah potongan tidak valid." });
|
|
1586
|
-
const zip =
|
|
1587
|
-
const out =
|
|
1588
|
-
const hash =
|
|
2688
|
+
const zip = path13.join(dir(job), "paket.zip");
|
|
2689
|
+
const out = fs17.createWriteStream(zip);
|
|
2690
|
+
const hash = crypto6.createHash("sha256");
|
|
1589
2691
|
let total = 0;
|
|
1590
2692
|
for (let i = 0;i < count; i++) {
|
|
1591
|
-
const f =
|
|
1592
|
-
if (!
|
|
2693
|
+
const f = path13.join(dir(job), `p${i}`);
|
|
2694
|
+
if (!fs17.existsSync(f))
|
|
1593
2695
|
return out.destroy(), json(req, res, 400, { galat: `Potongan ${i + 1} belum terunggah.` });
|
|
1594
2696
|
const part = await fsp4.readFile(f);
|
|
1595
2697
|
hash.update(part);
|
|
@@ -1619,8 +2721,8 @@ async function createRenderService(o) {
|
|
|
1619
2721
|
return json(req, res, 200, summary(t));
|
|
1620
2722
|
}
|
|
1621
2723
|
if (m[2] === "/hasil" && (req.method === "GET" || req.method === "HEAD")) {
|
|
1622
|
-
const f = t.hasilBerkas ?
|
|
1623
|
-
if (t.status !== "selesai" || !f || !
|
|
2724
|
+
const f = t.hasilBerkas ? path13.join(dir(job), t.hasilBerkas) : "";
|
|
2725
|
+
if (t.status !== "selesai" || !f || !fs17.existsSync(f))
|
|
1624
2726
|
return json(req, res, 409, { galat: "Video belum jadi." });
|
|
1625
2727
|
const webm = t.hasilJenis === "video/webm";
|
|
1626
2728
|
return sendFile(req, res, f, webm ? "video/webm" : "video/mp4", `hypeframe-${job}.${webm ? "webm" : "mp4"}`);
|
|
@@ -1651,7 +2753,7 @@ async function createRenderService(o) {
|
|
|
1651
2753
|
if (!JOB_ID.test(job))
|
|
1652
2754
|
continue;
|
|
1653
2755
|
try {
|
|
1654
|
-
const t = JSON.parse(await fsp4.readFile(
|
|
2756
|
+
const t = JSON.parse(await fsp4.readFile(path13.join(dir(job), "status.json"), "utf8"));
|
|
1655
2757
|
if (t.status === "jalan" || t.status === "antre")
|
|
1656
2758
|
update(t, { status: "gagal", galat: EngineError.Restarted });
|
|
1657
2759
|
jobs.set(job, t);
|
|
@@ -1685,7 +2787,7 @@ async function createRenderService(o) {
|
|
|
1685
2787
|
};
|
|
1686
2788
|
}
|
|
1687
2789
|
|
|
1688
|
-
//
|
|
2790
|
+
// src/ui/banner.ts
|
|
1689
2791
|
function banner() {
|
|
1690
2792
|
const mark = color.brand("◆");
|
|
1691
2793
|
return `
|
|
@@ -1694,8 +2796,8 @@ function banner() {
|
|
|
1694
2796
|
`;
|
|
1695
2797
|
}
|
|
1696
2798
|
|
|
1697
|
-
//
|
|
1698
|
-
function
|
|
2799
|
+
// src/util/format.ts
|
|
2800
|
+
function bytes2(n) {
|
|
1699
2801
|
if (!(n > 0))
|
|
1700
2802
|
return "0 B";
|
|
1701
2803
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
@@ -1731,13 +2833,22 @@ function table(rows, indent = " ") {
|
|
|
1731
2833
|
`);
|
|
1732
2834
|
}
|
|
1733
2835
|
|
|
1734
|
-
//
|
|
1735
|
-
import { spawn as
|
|
2836
|
+
// src/util/open.ts
|
|
2837
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
1736
2838
|
var PAIRING_LINK = new RegExp(`^https?://[A-Za-z0-9.-]+(:\\d+)?/sambung\\?kode=${PAIRING_CODE.source.slice(1, -1)}$`);
|
|
1737
2839
|
var WEB_ORIGIN = /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?\/?$/;
|
|
1738
|
-
function
|
|
1739
|
-
|
|
1740
|
-
|
|
2840
|
+
function openCommand(target, platform, url) {
|
|
2841
|
+
if (platform === "win32")
|
|
2842
|
+
return ["explorer.exe", [target]];
|
|
2843
|
+
if (platform === "darwin")
|
|
2844
|
+
return ["open", [target]];
|
|
2845
|
+
if (platform === "android")
|
|
2846
|
+
return [url ? "termux-open-url" : "termux-open", [target]];
|
|
2847
|
+
return ["xdg-open", [target]];
|
|
2848
|
+
}
|
|
2849
|
+
function launch(target, url) {
|
|
2850
|
+
const [cmd, args] = openCommand(target, isAndroid() ? "android" : process.platform, url);
|
|
2851
|
+
const p = spawn3(cmd, args, { stdio: "ignore", detached: true });
|
|
1741
2852
|
p.on("error", () => {
|
|
1742
2853
|
return;
|
|
1743
2854
|
});
|
|
@@ -1746,14 +2857,14 @@ function launch(target) {
|
|
|
1746
2857
|
function openUrl(url, allowed) {
|
|
1747
2858
|
if (!allowed.test(url))
|
|
1748
2859
|
return false;
|
|
1749
|
-
launch(url);
|
|
2860
|
+
launch(url, true);
|
|
1750
2861
|
return true;
|
|
1751
2862
|
}
|
|
1752
2863
|
function openFolder(dir) {
|
|
1753
|
-
launch(dir);
|
|
2864
|
+
launch(dir, false);
|
|
1754
2865
|
}
|
|
1755
2866
|
|
|
1756
|
-
//
|
|
2867
|
+
// src/cli/commands/start.ts
|
|
1757
2868
|
async function pairDevice(s, noBrowser = false) {
|
|
1758
2869
|
const a = await pair({
|
|
1759
2870
|
gateway: s.gateway,
|
|
@@ -1797,8 +2908,16 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1797
2908
|
account = await pairDevice(s, args.flags.noBrowser);
|
|
1798
2909
|
else
|
|
1799
2910
|
log.ok(t("pair.done", { email: color.bold(maskEmail(account.email)) }));
|
|
1800
|
-
|
|
1801
|
-
|
|
2911
|
+
let conn = null;
|
|
2912
|
+
let servicePort = 0;
|
|
2913
|
+
const agents = createAgentService({
|
|
2914
|
+
conn: { news: (k, b) => conn?.news(k, b), request: (ke, kind, body, ms) => conn?.request(ke, kind, body, ms) ?? Promise.resolve({ ok: false, error: "terputus" }) },
|
|
2915
|
+
port: () => servicePort,
|
|
2916
|
+
bridge: bridgeLaunch(),
|
|
2917
|
+
onToolError: (e) => log.warn(t(e === "tab" ? "agent.toolNoTab" : "agent.toolNoAnswer"))
|
|
2918
|
+
});
|
|
2919
|
+
const capabilities = { render: false, chrome: null, transparan: false, agen: agents.capabilities() };
|
|
2920
|
+
const key = crypto7.randomBytes(32).toString("base64url");
|
|
1802
2921
|
const cache = cacheDir();
|
|
1803
2922
|
const page = createPage({ web: s.web, cacheDir: cache });
|
|
1804
2923
|
let runner = null;
|
|
@@ -1808,13 +2927,13 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1808
2927
|
key,
|
|
1809
2928
|
origin: new URL(s.web).origin,
|
|
1810
2929
|
renderer: (task, o) => runner ? runner.renderer(task, o) : Promise.reject(new Error(EngineError.NotReady)),
|
|
1811
|
-
extraRoute: (req, res, url) => runner ? runner.route(req, res, url) : page.route(req, res, url),
|
|
2930
|
+
extraRoute: async (req, res, url) => await agents.route(req, res, url) || (runner ? runner.route(req, res, url) : page.route(req, res, url)),
|
|
1812
2931
|
onJob: (event, j) => {
|
|
1813
2932
|
if (event === "started") {
|
|
1814
2933
|
started.set(j.job, Date.now());
|
|
1815
2934
|
log.info(t("render.job", { kind: kindLabel(j), size: color.muted(`${j.tiket.w}×${j.tiket.h} · ${j.tiket.fps} fps · ${j.tiket.detik} s`) }));
|
|
1816
2935
|
} else if (event === "done") {
|
|
1817
|
-
log.ok(t("render.jobDone", { sec: seconds(Date.now() - (started.get(j.job) ?? Date.now())), size:
|
|
2936
|
+
log.ok(t("render.jobDone", { sec: seconds(Date.now() - (started.get(j.job) ?? Date.now())), size: bytes2(j.hasilUkuran ?? 0) }));
|
|
1818
2937
|
started.delete(j.job);
|
|
1819
2938
|
} else if (event === "failed") {
|
|
1820
2939
|
log.warn(t("render.jobFailed", { reason: j.galat || "?" }));
|
|
@@ -1825,17 +2944,28 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1825
2944
|
}
|
|
1826
2945
|
}
|
|
1827
2946
|
});
|
|
2947
|
+
servicePort = service.port;
|
|
1828
2948
|
const handler = createHandler({
|
|
1829
2949
|
status: () => ({ versi: VERSION, os: osName(), kemampuan: capabilities }),
|
|
1830
2950
|
kunci: () => {
|
|
1831
2951
|
if (!capabilities.render)
|
|
1832
2952
|
throw new Error(EngineError.NotReady);
|
|
1833
2953
|
return { port: service.port, kunci: key, versi: VERSION };
|
|
1834
|
-
}
|
|
2954
|
+
},
|
|
2955
|
+
...agents.work
|
|
1835
2956
|
});
|
|
1836
|
-
const
|
|
2957
|
+
const engineConn = new Connection({ gateway: s.gateway, token: account.token, info: { versi: VERSION, os: osName(), nama: s.name, kemampuan: capabilities, portLokal: service.port }, handler });
|
|
2958
|
+
conn = engineConn;
|
|
2959
|
+
setInterval(() => {
|
|
2960
|
+
const now = agents.capabilities();
|
|
2961
|
+
if (JSON.stringify(now) === JSON.stringify(capabilities.agen))
|
|
2962
|
+
return;
|
|
2963
|
+
capabilities.agen = now;
|
|
2964
|
+
conn?.setInfo({ kemampuan: capabilities });
|
|
2965
|
+
conn?.news("status", { kemampuan: capabilities });
|
|
2966
|
+
}, 30000).unref();
|
|
1837
2967
|
let connectedBefore = false;
|
|
1838
|
-
|
|
2968
|
+
engineConn.on("connected", () => {
|
|
1839
2969
|
if (connectedBefore)
|
|
1840
2970
|
log.ok(t("engine.reconnected"));
|
|
1841
2971
|
else {
|
|
@@ -1844,16 +2974,16 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1844
2974
|
}
|
|
1845
2975
|
connectedBefore = true;
|
|
1846
2976
|
});
|
|
1847
|
-
|
|
1848
|
-
|
|
2977
|
+
engineConn.on("disconnected", () => log.warn(t("engine.lost")));
|
|
2978
|
+
engineConn.on("revoked", () => {
|
|
1849
2979
|
log.warn(t("engine.revoked"));
|
|
1850
2980
|
process.exit(0);
|
|
1851
2981
|
});
|
|
1852
|
-
|
|
2982
|
+
engineConn.on("stopped", (reason) => {
|
|
1853
2983
|
log.error(reason === "protocol" ? t("engine.tooOld") : t("engine.replaced"));
|
|
1854
2984
|
process.exit(1);
|
|
1855
2985
|
});
|
|
1856
|
-
|
|
2986
|
+
engineConn.start();
|
|
1857
2987
|
let lastPercent = -10;
|
|
1858
2988
|
const chromeProgress = (percent, what) => {
|
|
1859
2989
|
if (percent === 0)
|
|
@@ -1880,8 +3010,8 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1880
3010
|
runner = createJobRunner({ chrome, ffmpeg, page, gpu: s.gpu, transparent: info.transparent, note: (m) => log.detail(m) });
|
|
1881
3011
|
runner.setPort(service.port);
|
|
1882
3012
|
Object.assign(capabilities, { render: true, chrome: info.version, transparan: info.transparent });
|
|
1883
|
-
|
|
1884
|
-
|
|
3013
|
+
engineConn.setInfo({ kemampuan: capabilities });
|
|
3014
|
+
engineConn.news("status", { kemampuan: capabilities });
|
|
1885
3015
|
log.ok(t("render.ready", { chrome: info.version, extra: info.transparent ? "" : t("render.noAlpha") }));
|
|
1886
3016
|
} catch (e) {
|
|
1887
3017
|
log.warn(t("render.notYet", { reason: e.message }));
|
|
@@ -1895,8 +3025,8 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1895
3025
|
const stop = () => {
|
|
1896
3026
|
console.log("");
|
|
1897
3027
|
log.info(t("engine.stopped"));
|
|
1898
|
-
|
|
1899
|
-
service.stop().finally(() => process.exit(0));
|
|
3028
|
+
engineConn.stop();
|
|
3029
|
+
Promise.all([service.stop(), agents.stop()]).finally(() => process.exit(0));
|
|
1900
3030
|
setTimeout(() => process.exit(0), 2000).unref();
|
|
1901
3031
|
};
|
|
1902
3032
|
process.once("SIGINT", stop);
|
|
@@ -1906,7 +3036,7 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
1906
3036
|
});
|
|
1907
3037
|
}
|
|
1908
3038
|
|
|
1909
|
-
//
|
|
3039
|
+
// src/cli/commands/account.ts
|
|
1910
3040
|
async function login(args) {
|
|
1911
3041
|
const s = resolveSettings(args.flags);
|
|
1912
3042
|
const a = readAccount();
|
|
@@ -1922,49 +3052,25 @@ function logout() {
|
|
|
1922
3052
|
log.ok(t("logout.done"));
|
|
1923
3053
|
}
|
|
1924
3054
|
|
|
1925
|
-
//
|
|
1926
|
-
import { spawnSync } from "node:child_process";
|
|
1927
|
-
import
|
|
3055
|
+
// src/cli/commands/autostart.ts
|
|
3056
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
3057
|
+
import fs18 from "node:fs";
|
|
1928
3058
|
import os3 from "node:os";
|
|
1929
|
-
import
|
|
1930
|
-
|
|
1931
|
-
// packages/hypeframe/src/util/runtime.ts
|
|
1932
|
-
import fs11 from "node:fs";
|
|
1933
|
-
import path8 from "node:path";
|
|
1934
|
-
function isStandalone() {
|
|
1935
|
-
return path8.basename(process.execPath).toLowerCase().startsWith("hypeframe");
|
|
1936
|
-
}
|
|
1937
|
-
function runtimeLabel() {
|
|
1938
|
-
const bun = process.versions.bun;
|
|
1939
|
-
return bun && !isStandalone() ? `Bun ${bun}` : isStandalone() ? `Bun ${bun ?? "?"} (standalone)` : `Node ${process.versions.node}`;
|
|
1940
|
-
}
|
|
1941
|
-
function launchCommand() {
|
|
1942
|
-
if (isStandalone())
|
|
1943
|
-
return [process.execPath];
|
|
1944
|
-
try {
|
|
1945
|
-
const script = fs11.realpathSync(process.argv[1] || "");
|
|
1946
|
-
return /[\\/]_npx[\\/]/.test(script) ? null : [process.execPath, script];
|
|
1947
|
-
} catch {
|
|
1948
|
-
return null;
|
|
1949
|
-
}
|
|
1950
|
-
}
|
|
1951
|
-
var INSTALL_URL = "https://hype-frame.com/install";
|
|
1952
|
-
|
|
1953
|
-
// packages/hypeframe/src/cli/commands/autostart.ts
|
|
3059
|
+
import path14 from "node:path";
|
|
1954
3060
|
function entryFile() {
|
|
1955
3061
|
const home = os3.homedir();
|
|
1956
3062
|
if (process.platform === "win32")
|
|
1957
|
-
return
|
|
3063
|
+
return path14.join(process.env.APPDATA || path14.join(home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "HypeFrame.cmd");
|
|
1958
3064
|
if (process.platform === "darwin")
|
|
1959
|
-
return
|
|
3065
|
+
return path14.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
|
|
1960
3066
|
if (hasSystemd())
|
|
1961
|
-
return
|
|
1962
|
-
return
|
|
3067
|
+
return path14.join(home, ".config", "systemd", "user", "hypeframe.service");
|
|
3068
|
+
return path14.join(home, ".config", "autostart", "hypeframe.desktop");
|
|
1963
3069
|
}
|
|
1964
3070
|
function hasSystemd() {
|
|
1965
|
-
return process.platform === "linux" &&
|
|
3071
|
+
return process.platform === "linux" && spawnSync2("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
|
|
1966
3072
|
}
|
|
1967
|
-
var autostartEnabled = () =>
|
|
3073
|
+
var autostartEnabled = () => fs18.existsSync(entryFile());
|
|
1968
3074
|
var xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1969
3075
|
function autostart(mode) {
|
|
1970
3076
|
const file = entryFile();
|
|
@@ -1975,8 +3081,8 @@ function autostart(mode) {
|
|
|
1975
3081
|
}
|
|
1976
3082
|
if (mode === "off") {
|
|
1977
3083
|
if (process.platform === "linux" && file.endsWith(".service"))
|
|
1978
|
-
|
|
1979
|
-
|
|
3084
|
+
spawnSync2("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
|
|
3085
|
+
fs18.rmSync(file, { force: true });
|
|
1980
3086
|
log.ok(t("autostart.off"));
|
|
1981
3087
|
return;
|
|
1982
3088
|
}
|
|
@@ -1991,14 +3097,14 @@ function autostart(mode) {
|
|
|
1991
3097
|
return;
|
|
1992
3098
|
}
|
|
1993
3099
|
const quoted = cmd.map((c) => `"${c}"`).join(" ");
|
|
1994
|
-
|
|
3100
|
+
fs18.mkdirSync(path14.dirname(file), { recursive: true });
|
|
1995
3101
|
if (process.platform === "win32") {
|
|
1996
|
-
|
|
3102
|
+
fs18.writeFileSync(file, `@echo off\r
|
|
1997
3103
|
start "HypeFrame" /min ${quoted} start --no-browser\r
|
|
1998
3104
|
`);
|
|
1999
3105
|
} else if (process.platform === "darwin") {
|
|
2000
|
-
const out =
|
|
2001
|
-
|
|
3106
|
+
const out = path14.join(logDir(), "autostart.log");
|
|
3107
|
+
fs18.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
|
|
2002
3108
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
2003
3109
|
<plist version="1.0"><dict>
|
|
2004
3110
|
<key>Label</key><string>com.hypeframe.engine</string>
|
|
@@ -2009,7 +3115,7 @@ start "HypeFrame" /min ${quoted} start --no-browser\r
|
|
|
2009
3115
|
</dict></plist>
|
|
2010
3116
|
`);
|
|
2011
3117
|
} else if (file.endsWith(".service")) {
|
|
2012
|
-
|
|
3118
|
+
fs18.writeFileSync(file, `[Unit]
|
|
2013
3119
|
Description=HypeFrame engine
|
|
2014
3120
|
After=network-online.target
|
|
2015
3121
|
|
|
@@ -2021,10 +3127,10 @@ RestartSec=60
|
|
|
2021
3127
|
[Install]
|
|
2022
3128
|
WantedBy=default.target
|
|
2023
3129
|
`);
|
|
2024
|
-
|
|
2025
|
-
|
|
3130
|
+
spawnSync2("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
3131
|
+
spawnSync2("systemctl", ["--user", "enable", "hypeframe.service"], { stdio: "ignore" });
|
|
2026
3132
|
} else {
|
|
2027
|
-
|
|
3133
|
+
fs18.writeFileSync(file, `[Desktop Entry]
|
|
2028
3134
|
Type=Application
|
|
2029
3135
|
Name=HypeFrame engine
|
|
2030
3136
|
Exec=${quoted} start --no-browser
|
|
@@ -2036,7 +3142,7 @@ X-GNOME-Autostart-enabled=true
|
|
|
2036
3142
|
log.detail(file);
|
|
2037
3143
|
}
|
|
2038
3144
|
|
|
2039
|
-
//
|
|
3145
|
+
// src/cli/commands/bench.ts
|
|
2040
3146
|
import http3 from "node:http";
|
|
2041
3147
|
import puppeteer3 from "puppeteer-core";
|
|
2042
3148
|
var FRAMES = 150;
|
|
@@ -2090,7 +3196,7 @@ async function bench(args) {
|
|
|
2090
3196
|
executablePath: chrome,
|
|
2091
3197
|
headless: true,
|
|
2092
3198
|
protocolTimeout: 300000,
|
|
2093
|
-
args: ["--no-first-run", "--disable-extensions", ...s.gpu ? [] : softwareGpuArgs]
|
|
3199
|
+
args: ["--no-first-run", "--disable-extensions", ...s.gpu ? [] : softwareGpuArgs, ...chromePlatformArgs()]
|
|
2094
3200
|
});
|
|
2095
3201
|
const rows = [];
|
|
2096
3202
|
try {
|
|
@@ -2122,8 +3228,353 @@ async function bench(args) {
|
|
|
2122
3228
|
`);
|
|
2123
3229
|
}
|
|
2124
3230
|
|
|
2125
|
-
//
|
|
3231
|
+
// src/cli/commands/agent.ts
|
|
2126
3232
|
import * as p from "@clack/prompts";
|
|
3233
|
+
|
|
3234
|
+
// src/agent/install.ts
|
|
3235
|
+
import fs19 from "node:fs";
|
|
3236
|
+
import fsp5 from "node:fs/promises";
|
|
3237
|
+
import path15 from "node:path";
|
|
3238
|
+
import yauzl2 from "yauzl";
|
|
3239
|
+
function unzip(file, to) {
|
|
3240
|
+
return new Promise((ok, fail) => {
|
|
3241
|
+
yauzl2.open(file, { lazyEntries: true }, (e, zip) => {
|
|
3242
|
+
if (e || !zip)
|
|
3243
|
+
return fail(e ?? new Error("zip"));
|
|
3244
|
+
zip.on("entry", (en) => {
|
|
3245
|
+
const target = path15.join(to, en.fileName);
|
|
3246
|
+
if (!target.startsWith(to + path15.sep))
|
|
3247
|
+
return fail(new Error("archive path outside the agent folder"));
|
|
3248
|
+
if (en.fileName.endsWith("/"))
|
|
3249
|
+
return fs19.mkdirSync(target, { recursive: true }), zip.readEntry();
|
|
3250
|
+
fs19.mkdirSync(path15.dirname(target), { recursive: true });
|
|
3251
|
+
zip.openReadStream(en, (e2, s) => {
|
|
3252
|
+
if (e2 || !s)
|
|
3253
|
+
return fail(e2 ?? new Error("zip"));
|
|
3254
|
+
const out = fs19.createWriteStream(target);
|
|
3255
|
+
s.pipe(out);
|
|
3256
|
+
out.on("finish", () => zip.readEntry());
|
|
3257
|
+
out.on("error", fail);
|
|
3258
|
+
});
|
|
3259
|
+
});
|
|
3260
|
+
zip.on("end", () => ok());
|
|
3261
|
+
zip.on("error", fail);
|
|
3262
|
+
zip.readEntry();
|
|
3263
|
+
});
|
|
3264
|
+
});
|
|
3265
|
+
}
|
|
3266
|
+
async function untarGz(file, to) {
|
|
3267
|
+
const { gunzipSync } = await import("node:zlib");
|
|
3268
|
+
const data = gunzipSync(await fsp5.readFile(file));
|
|
3269
|
+
const root = path15.resolve(to);
|
|
3270
|
+
const str = (b) => b.toString("utf8").replace(/\0[\s\S]*$/, "");
|
|
3271
|
+
const octal = (b) => Number.parseInt(str(b).trim() || "0", 8) || 0;
|
|
3272
|
+
let off = 0;
|
|
3273
|
+
let longName = null;
|
|
3274
|
+
while (off + 512 <= data.length) {
|
|
3275
|
+
const h = data.subarray(off, off + 512);
|
|
3276
|
+
if (h.every((x) => x === 0))
|
|
3277
|
+
break;
|
|
3278
|
+
const size = octal(h.subarray(124, 136));
|
|
3279
|
+
const type = String.fromCharCode(h[156] || 48);
|
|
3280
|
+
const body = data.subarray(off + 512, off + 512 + size);
|
|
3281
|
+
off += 512 + Math.ceil(size / 512) * 512;
|
|
3282
|
+
const prefix = str(h.subarray(345, 500));
|
|
3283
|
+
let name = longName ?? (prefix ? `${prefix}/${str(h.subarray(0, 100))}` : str(h.subarray(0, 100)));
|
|
3284
|
+
longName = null;
|
|
3285
|
+
if (type === "x") {
|
|
3286
|
+
const m = body.toString("utf8").match(/(?:^|\n)\d+ path=([^\n]*)\n/);
|
|
3287
|
+
if (m)
|
|
3288
|
+
longName = m[1];
|
|
3289
|
+
continue;
|
|
3290
|
+
}
|
|
3291
|
+
if (type === "L") {
|
|
3292
|
+
longName = str(body);
|
|
3293
|
+
continue;
|
|
3294
|
+
}
|
|
3295
|
+
if (type === "g")
|
|
3296
|
+
continue;
|
|
3297
|
+
name = name.replace(/^\.\//, "");
|
|
3298
|
+
if (!name)
|
|
3299
|
+
continue;
|
|
3300
|
+
const target = path15.resolve(root, name);
|
|
3301
|
+
if (target !== root && !target.startsWith(root + path15.sep))
|
|
3302
|
+
throw new Error("archive path outside the agent folder");
|
|
3303
|
+
if (type === "5") {
|
|
3304
|
+
await fsp5.mkdir(target, { recursive: true });
|
|
3305
|
+
continue;
|
|
3306
|
+
}
|
|
3307
|
+
if (type !== "0" && type !== "7")
|
|
3308
|
+
continue;
|
|
3309
|
+
await fsp5.mkdir(path15.dirname(target), { recursive: true });
|
|
3310
|
+
await fsp5.writeFile(target, body, { mode: octal(h.subarray(100, 108)) & 73 ? 493 : 420 });
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
function npxRunner(pkg, extra = []) {
|
|
3314
|
+
if (isStandalone())
|
|
3315
|
+
return { cmd: process.execPath, args: ["x", pkg, ...extra], env: { BUN_BE_BUN: "1" } };
|
|
3316
|
+
const npxCli = path15.join(path15.dirname(process.execPath), process.platform === "win32" ? "" : "..", process.platform === "win32" ? "node_modules" : "lib/node_modules", "npm", "bin", "npx-cli.js");
|
|
3317
|
+
if (!fs19.existsSync(npxCli))
|
|
3318
|
+
throw new Error("npx was not found next to Node.js");
|
|
3319
|
+
return { cmd: process.execPath, args: [npxCli, "-y", pkg, ...extra], env: {} };
|
|
3320
|
+
}
|
|
3321
|
+
function ownCopy(a) {
|
|
3322
|
+
const bin = a.distribution.binary?.[platformKey()];
|
|
3323
|
+
if (bin) {
|
|
3324
|
+
const cmd = onPath(path15.basename(bin.cmd).replace(/\.exe$/i, ""));
|
|
3325
|
+
return cmd ? { cmd, args: bin.args ?? [], env: bin.env ?? {} } : null;
|
|
3326
|
+
}
|
|
3327
|
+
const npx = a.distribution.npx;
|
|
3328
|
+
if (npx) {
|
|
3329
|
+
const name = npx.package.replace(/(?!^)@[^@/]*$/, "").split("/").pop() ?? "";
|
|
3330
|
+
const cmd = onPath(name);
|
|
3331
|
+
return cmd ? { cmd, args: npx.args ?? [], env: npx.env ?? {} } : null;
|
|
3332
|
+
}
|
|
3333
|
+
return null;
|
|
3334
|
+
}
|
|
3335
|
+
async function installAgent(id, progress = () => {
|
|
3336
|
+
return;
|
|
3337
|
+
}, opts = {}) {
|
|
3338
|
+
const a = (await fetchRegistry()).find((x) => x.id === id);
|
|
3339
|
+
if (!a)
|
|
3340
|
+
throw new Error(`Agent ${id} is not in the registry`);
|
|
3341
|
+
const local = a.distribution.local;
|
|
3342
|
+
if (!isSupported(id) && !local)
|
|
3343
|
+
throw new Error(`Agent ${id} is not supported`);
|
|
3344
|
+
let launch;
|
|
3345
|
+
const bin = a.distribution.binary?.[platformKey()];
|
|
3346
|
+
const own = local || opts.download ? null : ownCopy(a);
|
|
3347
|
+
if (local) {
|
|
3348
|
+
launch = { cmd: local.cmd, args: local.args ?? [], env: {} };
|
|
3349
|
+
} else if (own) {
|
|
3350
|
+
launch = own;
|
|
3351
|
+
} else if (bin) {
|
|
3352
|
+
if (!/^[0-9a-f]{64}$/i.test(bin.sha256 || ""))
|
|
3353
|
+
throw new Error(`Agent ${id}: the registry gives no sha256; not installed`);
|
|
3354
|
+
const dir = path15.join(agentDir(), id, a.version);
|
|
3355
|
+
const tmp = `${dir}.tmp`;
|
|
3356
|
+
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
3357
|
+
await fsp5.mkdir(tmp, { recursive: true });
|
|
3358
|
+
try {
|
|
3359
|
+
const name = path15.basename(new URL(bin.archive).pathname);
|
|
3360
|
+
const cmdRel = bin.cmd.replace(/^\.\//, "");
|
|
3361
|
+
if (/\.zip$/i.test(name)) {
|
|
3362
|
+
const file = path15.join(tmp, ".download.zip");
|
|
3363
|
+
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
|
|
3364
|
+
await unzip(file, tmp);
|
|
3365
|
+
await fsp5.rm(file, { force: true });
|
|
3366
|
+
} else if (/\.(tar\.gz|tgz)$/i.test(name)) {
|
|
3367
|
+
const file = path15.join(tmp, ".download.tar.gz");
|
|
3368
|
+
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
|
|
3369
|
+
await untarGz(file, tmp);
|
|
3370
|
+
await fsp5.rm(file, { force: true });
|
|
3371
|
+
} else if (/\.gz$/i.test(name)) {
|
|
3372
|
+
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), path15.join(tmp, cmdRel), progress, true);
|
|
3373
|
+
} else
|
|
3374
|
+
throw new Error(`Agent ${id}: unsupported archive ${name}`);
|
|
3375
|
+
const cmd = path15.join(tmp, cmdRel);
|
|
3376
|
+
if (!fs19.existsSync(cmd))
|
|
3377
|
+
throw new Error(`Agent ${id}: ${bin.cmd} is not in the download`);
|
|
3378
|
+
if (process.platform !== "win32")
|
|
3379
|
+
await fsp5.chmod(cmd, 493);
|
|
3380
|
+
await fsp5.rm(dir, { recursive: true, force: true });
|
|
3381
|
+
await fsp5.rename(tmp, dir);
|
|
3382
|
+
launch = { cmd: path15.join(dir, cmdRel), args: bin.args ?? [], env: bin.env ?? {} };
|
|
3383
|
+
} catch (e) {
|
|
3384
|
+
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
3385
|
+
throw e;
|
|
3386
|
+
}
|
|
3387
|
+
} else if (a.distribution.npx) {
|
|
3388
|
+
launch = { ...npxRunner(a.distribution.npx.package, a.distribution.npx.args), env: { ...a.distribution.npx.env ?? {} } };
|
|
3389
|
+
if (isStandalone())
|
|
3390
|
+
launch.env.BUN_BE_BUN = "1";
|
|
3391
|
+
} else
|
|
3392
|
+
throw new Error(`Agent ${id} has no download for ${platformKey()}`);
|
|
3393
|
+
const installed = { id, name: a.name, version: a.version, launch, ...own ? { own: true } : {} };
|
|
3394
|
+
writeInstalled(installed);
|
|
3395
|
+
return installed;
|
|
3396
|
+
}
|
|
3397
|
+
|
|
3398
|
+
// src/agent/login.ts
|
|
3399
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
3400
|
+
async function keyFromShell(name, io) {
|
|
3401
|
+
const value = process.env[name];
|
|
3402
|
+
if (!value)
|
|
3403
|
+
return null;
|
|
3404
|
+
if (io.confirm)
|
|
3405
|
+
return await io.confirm(t("agent.keyFromShellAsk", { name })) ? value : null;
|
|
3406
|
+
io.say(t("agent.keyFromShell", { name }));
|
|
3407
|
+
return value;
|
|
3408
|
+
}
|
|
3409
|
+
async function checkReady(id) {
|
|
3410
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
3411
|
+
if (!a)
|
|
3412
|
+
return false;
|
|
3413
|
+
const proc = new AcpProcess;
|
|
3414
|
+
try {
|
|
3415
|
+
await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
3416
|
+
await proc.request("session/new", { cwd: projectDir("_cek"), mcpServers: [] }, 90000);
|
|
3417
|
+
setReady(id, true);
|
|
3418
|
+
return true;
|
|
3419
|
+
} catch {
|
|
3420
|
+
setReady(id, false);
|
|
3421
|
+
return false;
|
|
3422
|
+
} finally {
|
|
3423
|
+
await proc.stop();
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
var isKey = (m) => m.type === "env_var" || !!m.varName;
|
|
3427
|
+
function pick(methods) {
|
|
3428
|
+
return methods.find((m) => m.type === "terminal") ?? methods.find((m) => (!m.type || m.type === "agent") && !isKey(m)) ?? methods.find(isKey);
|
|
3429
|
+
}
|
|
3430
|
+
async function loginAgent(id, io) {
|
|
3431
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
3432
|
+
if (!a)
|
|
3433
|
+
throw new Error(`Agent ${id} is not installed`);
|
|
3434
|
+
const proc = new AcpProcess;
|
|
3435
|
+
let method;
|
|
3436
|
+
try {
|
|
3437
|
+
const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
3438
|
+
method = pick(init.authMethods ?? []);
|
|
3439
|
+
if (method && (!method.type || method.type === "agent") && !isKey(method))
|
|
3440
|
+
await proc.request("authenticate", { methodId: method.id }, 10 * 60000);
|
|
3441
|
+
} finally {
|
|
3442
|
+
await proc.stop();
|
|
3443
|
+
}
|
|
3444
|
+
if (method?.type === "terminal") {
|
|
3445
|
+
io.say(method.name || method.description || id);
|
|
3446
|
+
const r = spawnSync3(a.launch.cmd, [...a.launch.args, ...method.args ?? []], { stdio: "inherit", env: { ...process.env, ...a.launch.env, ...agentEnv(id), ...method.env ?? {} } });
|
|
3447
|
+
if (r.status !== 0)
|
|
3448
|
+
return setReady(id, false), false;
|
|
3449
|
+
} else if (method && isKey(method)) {
|
|
3450
|
+
const name = method.varName || method.id;
|
|
3451
|
+
const value = await keyFromShell(name, io) || await io.ask(name);
|
|
3452
|
+
if (!value)
|
|
3453
|
+
return false;
|
|
3454
|
+
saveAgentEnv(id, { [name]: value.trim() });
|
|
3455
|
+
}
|
|
3456
|
+
return checkReady(id);
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
// src/cli/commands/agent.ts
|
|
3460
|
+
var NAMES = { "antigravity-acp": "Antigravity", "codex-acp": "Codex", opencode: "OpenCode" };
|
|
3461
|
+
var agentName = (id) => NAMES[id] ?? readInstalled().find((a) => a.id === id)?.name ?? id;
|
|
3462
|
+
function agentState(id) {
|
|
3463
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
3464
|
+
return !a ? "none" : a.ready ? "ready" : "login";
|
|
3465
|
+
}
|
|
3466
|
+
var stateText = (s) => s === "ready" ? color.ok(t("agent.ready")) : s === "login" ? color.warn(t("agent.needLogin")) : color.muted(t("agent.notInstalled"));
|
|
3467
|
+
var io = {
|
|
3468
|
+
ask: async (label) => {
|
|
3469
|
+
if (!process.stdin.isTTY)
|
|
3470
|
+
return null;
|
|
3471
|
+
const v = await p.password({ message: t("agent.askKey", { name: label }) });
|
|
3472
|
+
return p.isCancel(v) || !v ? null : String(v);
|
|
3473
|
+
},
|
|
3474
|
+
say: (s) => log.info(s),
|
|
3475
|
+
...process.stdin.isTTY ? {
|
|
3476
|
+
confirm: async (question) => {
|
|
3477
|
+
const v = await p.confirm({ message: question });
|
|
3478
|
+
return !p.isCancel(v) && v === true;
|
|
3479
|
+
}
|
|
3480
|
+
} : {}
|
|
3481
|
+
};
|
|
3482
|
+
function ids() {
|
|
3483
|
+
return [...new Set([...SUPPORTED_AGENTS, ...readInstalled().map((a) => a.id)])];
|
|
3484
|
+
}
|
|
3485
|
+
function listAgents() {
|
|
3486
|
+
console.log("");
|
|
3487
|
+
const info = (id) => {
|
|
3488
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
3489
|
+
return a ? color.muted(` ${icon.dot} ${a.own ? t("agent.ownTag") : a.version}`) : "";
|
|
3490
|
+
};
|
|
3491
|
+
console.log(table(ids().map((id) => [color.muted(agentName(id)), `${stateText(agentState(id))}${info(id)}`])));
|
|
3492
|
+
console.log(`
|
|
3493
|
+
${color.muted(t("agent.webHint"))}
|
|
3494
|
+
`);
|
|
3495
|
+
}
|
|
3496
|
+
async function addAgent(id, download = false) {
|
|
3497
|
+
const known = isSupported(id) || (await fetchRegistry()).some((a) => a.id === id && a.distribution.local);
|
|
3498
|
+
if (!known)
|
|
3499
|
+
return log.error(t("agent.unknown", { id, list: SUPPORTED_AGENTS.join(", ") })), false;
|
|
3500
|
+
log.info(t("agent.installing", { name: agentName(id) }));
|
|
3501
|
+
let last = -10;
|
|
3502
|
+
const a = await installAgent(id, (pc) => {
|
|
3503
|
+
if (pc - last >= 20)
|
|
3504
|
+
last = pc, log.detail(`${pc}%`);
|
|
3505
|
+
}, { download });
|
|
3506
|
+
if (a.own)
|
|
3507
|
+
log.ok(t("agent.own", { name: a.name, path: a.launch.cmd }));
|
|
3508
|
+
else
|
|
3509
|
+
log.ok(t("agent.installed", { name: a.name, version: a.version }));
|
|
3510
|
+
const ok = await loginOne(id);
|
|
3511
|
+
if (!ok && a.own)
|
|
3512
|
+
log.detail(t("agent.ownFailed", { name: a.name, id }));
|
|
3513
|
+
return ok;
|
|
3514
|
+
}
|
|
3515
|
+
async function loginOne(id) {
|
|
3516
|
+
log.info(t("agent.loggingIn", { name: agentName(id) }));
|
|
3517
|
+
const ok = await loginAgent(id, io);
|
|
3518
|
+
if (ok)
|
|
3519
|
+
log.ok(t("agent.loggedIn", { name: agentName(id) }));
|
|
3520
|
+
else
|
|
3521
|
+
log.warn(t("agent.loginFailed", { name: agentName(id) }));
|
|
3522
|
+
return ok;
|
|
3523
|
+
}
|
|
3524
|
+
async function agentCommand(args) {
|
|
3525
|
+
const [sub, id] = args.rest;
|
|
3526
|
+
if (!sub || sub === "list")
|
|
3527
|
+
return listAgents();
|
|
3528
|
+
if (!id)
|
|
3529
|
+
return log.error("hypeframe agent add|login|remove <id>");
|
|
3530
|
+
if (sub === "add")
|
|
3531
|
+
return void await addAgent(id, args.flags.download === true);
|
|
3532
|
+
if (sub === "login") {
|
|
3533
|
+
if (agentState(id) === "none")
|
|
3534
|
+
return log.error(t("agent.notInstalledYet", { name: agentName(id) }));
|
|
3535
|
+
return void await loginOne(id);
|
|
3536
|
+
}
|
|
3537
|
+
if (sub === "remove") {
|
|
3538
|
+
removeAgent(id);
|
|
3539
|
+
return log.ok(t("agent.removed", { name: agentName(id) }));
|
|
3540
|
+
}
|
|
3541
|
+
log.error("hypeframe agent list|add|login|remove <id>");
|
|
3542
|
+
}
|
|
3543
|
+
async function agentMenu() {
|
|
3544
|
+
for (;; ) {
|
|
3545
|
+
const choice = await p.select({
|
|
3546
|
+
message: t("agent.menuQuestion"),
|
|
3547
|
+
options: [...ids().map((id) => ({ value: id, label: agentName(id), hint: t(agentState(id) === "ready" ? "agent.ready" : agentState(id) === "login" ? "agent.needLogin" : "agent.notInstalled") })), { value: "", label: color.muted(t("agent.back")) }]
|
|
3548
|
+
});
|
|
3549
|
+
if (p.isCancel(choice) || !choice)
|
|
3550
|
+
return;
|
|
3551
|
+
const state = agentState(choice);
|
|
3552
|
+
const action = await p.select({
|
|
3553
|
+
message: agentName(choice),
|
|
3554
|
+
options: [
|
|
3555
|
+
...state === "none" ? [{ value: "add", label: t("agent.add") }] : [],
|
|
3556
|
+
...state !== "none" ? [{ value: "login", label: t("agent.login") }] : [],
|
|
3557
|
+
...state !== "none" ? [{ value: "remove", label: t("agent.remove") }] : [],
|
|
3558
|
+
{ value: "", label: color.muted(t("agent.back")) }
|
|
3559
|
+
]
|
|
3560
|
+
});
|
|
3561
|
+
if (p.isCancel(action) || !action)
|
|
3562
|
+
continue;
|
|
3563
|
+
try {
|
|
3564
|
+
if (action === "add")
|
|
3565
|
+
await addAgent(choice);
|
|
3566
|
+
if (action === "login")
|
|
3567
|
+
await loginOne(choice);
|
|
3568
|
+
if (action === "remove")
|
|
3569
|
+
removeAgent(choice), log.ok(t("agent.removed", { name: agentName(choice) }));
|
|
3570
|
+
} catch (e) {
|
|
3571
|
+
log.error(e.message);
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
|
|
3576
|
+
// src/cli/commands/config.ts
|
|
3577
|
+
import * as p2 from "@clack/prompts";
|
|
2127
3578
|
function print() {
|
|
2128
3579
|
const s = resolveSettings();
|
|
2129
3580
|
const saved = readSettings();
|
|
@@ -2165,13 +3616,13 @@ async function config(args) {
|
|
|
2165
3616
|
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
2166
3617
|
return print();
|
|
2167
3618
|
const s = resolveSettings();
|
|
2168
|
-
const name = await
|
|
2169
|
-
if (
|
|
3619
|
+
const name = await p2.text({ message: t("config.name"), initialValue: s.name, validate: (v) => v && v.trim() ? undefined : "—" });
|
|
3620
|
+
if (p2.isCancel(name))
|
|
2170
3621
|
return;
|
|
2171
|
-
const gpu = await
|
|
2172
|
-
if (
|
|
3622
|
+
const gpu = await p2.confirm({ message: t("config.gpu"), initialValue: s.gpu });
|
|
3623
|
+
if (p2.isCancel(gpu))
|
|
2173
3624
|
return;
|
|
2174
|
-
const language = await
|
|
3625
|
+
const language = await p2.select({
|
|
2175
3626
|
message: t("config.language"),
|
|
2176
3627
|
initialValue: readSettings().language ?? "auto",
|
|
2177
3628
|
options: [
|
|
@@ -2180,7 +3631,7 @@ async function config(args) {
|
|
|
2180
3631
|
{ value: "en", label: "English" }
|
|
2181
3632
|
]
|
|
2182
3633
|
});
|
|
2183
|
-
if (
|
|
3634
|
+
if (p2.isCancel(language))
|
|
2184
3635
|
return;
|
|
2185
3636
|
saveSettings({ name: String(name).trim().slice(0, 40), gpu: !!gpu, language });
|
|
2186
3637
|
resetLang();
|
|
@@ -2188,10 +3639,10 @@ async function config(args) {
|
|
|
2188
3639
|
log.detail(t("config.restart"));
|
|
2189
3640
|
}
|
|
2190
3641
|
|
|
2191
|
-
//
|
|
2192
|
-
import { spawnSync as
|
|
2193
|
-
import
|
|
2194
|
-
import
|
|
3642
|
+
// src/cli/commands/doctor.ts
|
|
3643
|
+
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
3644
|
+
import fs20 from "node:fs";
|
|
3645
|
+
import path16 from "node:path";
|
|
2195
3646
|
var mark = { ok: color.ok(icon.ok), warn: color.warn(icon.warn), error: color.error(icon.error) };
|
|
2196
3647
|
async function reach(url) {
|
|
2197
3648
|
const t0 = Date.now();
|
|
@@ -2220,12 +3671,12 @@ async function doctor(args) {
|
|
|
2220
3671
|
show({ label: "Node.js", result: maj > 20 || maj === 20 && min >= 3 ? "ok" : "error", detail: `${process.versions.node}${maj < 20 || maj === 20 && min < 3 ? ` ${t("doctor.nodeOld")}` : ""}` });
|
|
2221
3672
|
}
|
|
2222
3673
|
try {
|
|
2223
|
-
const probe =
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
const st =
|
|
3674
|
+
const probe = path16.join(dataDir(), `.probe-${process.pid}`);
|
|
3675
|
+
fs20.writeFileSync(probe, "x");
|
|
3676
|
+
fs20.rmSync(probe);
|
|
3677
|
+
const st = fs20.statfsSync(dataDir());
|
|
2227
3678
|
const free = st.bavail * st.bsize;
|
|
2228
|
-
show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size:
|
|
3679
|
+
show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size: bytes2(free) })}` });
|
|
2229
3680
|
} catch (e) {
|
|
2230
3681
|
show({ label: t("doctor.disk"), result: "error", detail: e.message });
|
|
2231
3682
|
}
|
|
@@ -2234,7 +3685,7 @@ async function doctor(args) {
|
|
|
2234
3685
|
const canDownload = !!FFMPEG_PINNED[`${process.platform}-${process.arch}`];
|
|
2235
3686
|
show({ label: "ffmpeg", result: canDownload ? "warn" : "error", detail: canDownload ? t("doctor.ffmpegLater") : t("doctor.noFfmpeg") });
|
|
2236
3687
|
} else {
|
|
2237
|
-
const r =
|
|
3688
|
+
const r = spawnSync4(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
|
|
2238
3689
|
const v = /ffmpeg version (\S+)/.exec(r.stdout || "")?.[1];
|
|
2239
3690
|
show({ label: "ffmpeg", result: v ? "ok" : "error", detail: v || t("doctor.noFfmpeg") });
|
|
2240
3691
|
}
|
|
@@ -2266,22 +3717,22 @@ async function doctor(args) {
|
|
|
2266
3717
|
return checks;
|
|
2267
3718
|
}
|
|
2268
3719
|
|
|
2269
|
-
//
|
|
2270
|
-
import
|
|
2271
|
-
import
|
|
2272
|
-
function
|
|
3720
|
+
// src/cli/commands/history.ts
|
|
3721
|
+
import fs21 from "node:fs";
|
|
3722
|
+
import path17 from "node:path";
|
|
3723
|
+
function readHistory2(hours = 24) {
|
|
2273
3724
|
const root = renderDir();
|
|
2274
3725
|
const since = Date.now() - hours * 3600000;
|
|
2275
3726
|
const out = [];
|
|
2276
|
-
for (const name of
|
|
3727
|
+
for (const name of fs21.readdirSync(root)) {
|
|
2277
3728
|
if (!JOB_ID.test(name))
|
|
2278
3729
|
continue;
|
|
2279
3730
|
try {
|
|
2280
|
-
const j = JSON.parse(
|
|
3731
|
+
const j = JSON.parse(fs21.readFileSync(path17.join(root, name, "status.json"), "utf8"));
|
|
2281
3732
|
if ((j.diperbarui || j.dibuat) < since)
|
|
2282
3733
|
continue;
|
|
2283
|
-
const f = j.hasilBerkas ?
|
|
2284
|
-
out.push({ job: j, file: f &&
|
|
3734
|
+
const f = j.hasilBerkas ? path17.join(root, name, j.hasilBerkas) : null;
|
|
3735
|
+
out.push({ job: j, file: f && fs21.existsSync(f) ? f : null });
|
|
2285
3736
|
} catch {}
|
|
2286
3737
|
}
|
|
2287
3738
|
return out.sort((a, b) => (b.job.diperbarui || 0) - (a.job.diperbarui || 0));
|
|
@@ -2291,12 +3742,12 @@ function formatItem({ job: j, file }) {
|
|
|
2291
3742
|
const mark = j.status === "selesai" ? color.ok(icon.ok) : j.status === "gagal" ? color.error(icon.error) : j.status === "batal" ? color.muted(icon.dot) : color.info(icon.info);
|
|
2292
3743
|
const kind = j.tiket.jenis === "klip" ? t("render.kindClip") : t("render.kindVideo");
|
|
2293
3744
|
const took = j.selesaiPada && j.mulaiPada ? ` ${color.muted(icon.dot)} ${seconds(j.selesaiPada - j.mulaiPada)}` : "";
|
|
2294
|
-
const detail = j.status === "selesai" ? `${
|
|
3745
|
+
const detail = j.status === "selesai" ? `${bytes2(j.hasilUkuran ?? 0)}${took}` : j.status === "gagal" ? color.error(String(j.galat || "").slice(0, 70)) : j.status === "batal" ? color.muted(t("history.cancelled")) : color.info(`${j.persen ?? 0}%`);
|
|
2295
3746
|
return `${color.muted(time2(j.diperbarui || j.dibuat))} ${mark} ${kind} ${color.muted(`${j.tiket.w}×${j.tiket.h}`)} ${detail}${file ? `
|
|
2296
3747
|
${color.muted(icon.detail)} ${color.muted(file)}` : ""}`;
|
|
2297
3748
|
}
|
|
2298
3749
|
function history() {
|
|
2299
|
-
const items =
|
|
3750
|
+
const items = readHistory2();
|
|
2300
3751
|
console.log("");
|
|
2301
3752
|
if (!items.length)
|
|
2302
3753
|
console.log(` ${color.muted(t("history.empty"))}`);
|
|
@@ -2306,41 +3757,41 @@ function history() {
|
|
|
2306
3757
|
return items;
|
|
2307
3758
|
}
|
|
2308
3759
|
|
|
2309
|
-
//
|
|
2310
|
-
import { spawnSync as
|
|
2311
|
-
import
|
|
3760
|
+
// src/cli/commands/maintenance.ts
|
|
3761
|
+
import { spawnSync as spawnSync5 } from "node:child_process";
|
|
3762
|
+
import fs22 from "node:fs";
|
|
2312
3763
|
import os4 from "node:os";
|
|
2313
|
-
import
|
|
3764
|
+
import path18 from "node:path";
|
|
2314
3765
|
async function clean() {
|
|
2315
3766
|
if (runningPid()) {
|
|
2316
3767
|
log.warn(t("clean.running"));
|
|
2317
3768
|
return;
|
|
2318
3769
|
}
|
|
2319
|
-
const targets = [
|
|
2320
|
-
for (const job of
|
|
3770
|
+
const targets = [path18.join(cacheDir(), "chrome"), path18.join(cacheDir(), "halaman"), path18.join(logDir(), "hypeframe.log.1")];
|
|
3771
|
+
for (const job of fs22.readdirSync(renderDir())) {
|
|
2321
3772
|
if (!JOB_ID.test(job))
|
|
2322
3773
|
continue;
|
|
2323
3774
|
try {
|
|
2324
|
-
const s = JSON.parse(
|
|
3775
|
+
const s = JSON.parse(fs22.readFileSync(path18.join(renderDir(), job, "status.json"), "utf8")).status;
|
|
2325
3776
|
if (s === "gagal" || s === "batal" || s === "unggah")
|
|
2326
|
-
targets.push(
|
|
3777
|
+
targets.push(path18.join(renderDir(), job));
|
|
2327
3778
|
} catch {
|
|
2328
|
-
targets.push(
|
|
3779
|
+
targets.push(path18.join(renderDir(), job));
|
|
2329
3780
|
}
|
|
2330
3781
|
}
|
|
2331
3782
|
let freed = 0;
|
|
2332
3783
|
for (const p of targets) {
|
|
2333
3784
|
freed += await sizeOf(p);
|
|
2334
|
-
|
|
3785
|
+
fs22.rmSync(p, { recursive: true, force: true });
|
|
2335
3786
|
}
|
|
2336
|
-
log.ok(t("clean.done", { size:
|
|
3787
|
+
log.ok(t("clean.done", { size: bytes2(freed) }));
|
|
2337
3788
|
}
|
|
2338
3789
|
function report() {
|
|
2339
3790
|
const s = resolveSettings();
|
|
2340
3791
|
const a = readAccount();
|
|
2341
3792
|
let recent = "";
|
|
2342
3793
|
try {
|
|
2343
|
-
recent =
|
|
3794
|
+
recent = fs22.readFileSync(path18.join(logDir(), "hypeframe.log"), "utf8").split(`
|
|
2344
3795
|
`).slice(-400).join(`
|
|
2345
3796
|
`);
|
|
2346
3797
|
} catch {
|
|
@@ -2349,7 +3800,7 @@ function report() {
|
|
|
2349
3800
|
const lines = [
|
|
2350
3801
|
`hypeframe ${VERSION}`,
|
|
2351
3802
|
`created ${new Date().toISOString()}`,
|
|
2352
|
-
`${runtimeLabel()} · ${process.platform} ${os4.release()} ${process.arch} · ${os4.cpus()[0]?.model ?? "?"} ×${os4.cpus().length} · ${
|
|
3803
|
+
`${runtimeLabel()} · ${process.platform} ${os4.release()} ${process.arch} · ${os4.cpus()[0]?.model ?? "?"} ×${os4.cpus().length} · ${bytes2(os4.totalmem())} RAM`,
|
|
2353
3804
|
`gateway ${s.gateway}`,
|
|
2354
3805
|
`web ${s.web}`,
|
|
2355
3806
|
`gpu ${s.gpu}`,
|
|
@@ -2361,13 +3812,20 @@ function report() {
|
|
|
2361
3812
|
recent
|
|
2362
3813
|
];
|
|
2363
3814
|
const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
|
|
2364
|
-
const file =
|
|
2365
|
-
|
|
3815
|
+
const file = path18.join(dataDir(), `laporan-${stamp}.txt`);
|
|
3816
|
+
fs22.writeFileSync(file, mask(lines.join(`
|
|
2366
3817
|
`)), { mode: 384 });
|
|
2367
3818
|
log.ok(t("report.done", { file }));
|
|
2368
3819
|
log.detail(t("report.hint"));
|
|
2369
3820
|
return file;
|
|
2370
3821
|
}
|
|
3822
|
+
function updateCommand(o) {
|
|
3823
|
+
if (o.standalone && o.windows)
|
|
3824
|
+
return ["powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_URL}.ps1 | iex`], {}];
|
|
3825
|
+
if (o.standalone || o.android)
|
|
3826
|
+
return ["bash", ["-c", `curl -fsSL ${INSTALL_URL} | bash`], {}];
|
|
3827
|
+
return ["npm", ["i", "-g", "hypeframe@latest"], { shell: o.windows }];
|
|
3828
|
+
}
|
|
2371
3829
|
function update() {
|
|
2372
3830
|
if (!launchCommand()) {
|
|
2373
3831
|
log.info(t("update.npx"));
|
|
@@ -2375,8 +3833,8 @@ function update() {
|
|
|
2375
3833
|
return;
|
|
2376
3834
|
}
|
|
2377
3835
|
log.info(t("update.running"));
|
|
2378
|
-
const
|
|
2379
|
-
const r =
|
|
3836
|
+
const [cmd, args, extra] = updateCommand({ standalone: isStandalone(), android: isAndroid(), windows: process.platform === "win32" });
|
|
3837
|
+
const r = spawnSync5(cmd, args, { stdio: "inherit", ...extra });
|
|
2380
3838
|
if (r.status === 0)
|
|
2381
3839
|
log.ok(t("update.done"));
|
|
2382
3840
|
else
|
|
@@ -2390,15 +3848,15 @@ function openWeb(args) {
|
|
|
2390
3848
|
log.warn(t("pair.badWeb"));
|
|
2391
3849
|
}
|
|
2392
3850
|
|
|
2393
|
-
//
|
|
2394
|
-
import
|
|
2395
|
-
import
|
|
3851
|
+
// src/cli/commands/status.ts
|
|
3852
|
+
import fs23 from "node:fs";
|
|
3853
|
+
import path19 from "node:path";
|
|
2396
3854
|
function statusRows(args) {
|
|
2397
3855
|
const s = resolveSettings(args?.flags);
|
|
2398
3856
|
const a = readAccount();
|
|
2399
3857
|
const pid = runningPid();
|
|
2400
|
-
const chrome = findChrome() ||
|
|
2401
|
-
const recent =
|
|
3858
|
+
const chrome = findChrome() || fs23.existsSync(path19.join(cacheDir(), "chrome"));
|
|
3859
|
+
const recent = readHistory2();
|
|
2402
3860
|
const k = (key) => color.muted(t(key));
|
|
2403
3861
|
return [
|
|
2404
3862
|
[k("status.account"), a && a.gateway === s.gateway ? `${color.ok(icon.ok)} ${maskEmail(a.email)}` : `${color.warn(icon.warn)} ${t("status.notPaired")}`],
|
|
@@ -2415,8 +3873,8 @@ function status(args) {
|
|
|
2415
3873
|
console.log("");
|
|
2416
3874
|
}
|
|
2417
3875
|
|
|
2418
|
-
//
|
|
2419
|
-
import * as
|
|
3876
|
+
// src/cli/menu.ts
|
|
3877
|
+
import * as p3 from "@clack/prompts";
|
|
2420
3878
|
async function menu(args) {
|
|
2421
3879
|
process.stdout.write(banner());
|
|
2422
3880
|
console.log("");
|
|
@@ -2426,14 +3884,17 @@ async function menu(args) {
|
|
|
2426
3884
|
const s = resolveSettings(args.flags);
|
|
2427
3885
|
const paired = !!readAccount() && readAccount()?.gateway === s.gateway;
|
|
2428
3886
|
const running = !!runningPid();
|
|
2429
|
-
const choice = await
|
|
3887
|
+
const choice = await p3.select({
|
|
2430
3888
|
message: t("menu.question"),
|
|
2431
3889
|
options: [
|
|
2432
3890
|
{ value: "start", label: color.brand(t("menu.start")), hint: running ? t("status.running", { pid: runningPid() ?? "" }) : paired ? undefined : t("menu.startPair") },
|
|
2433
3891
|
{ value: "open", label: t("menu.open"), hint: s.web.replace(/^https?:\/\//, "") },
|
|
2434
3892
|
{ value: "bench", label: t("menu.bench") },
|
|
2435
3893
|
{ value: "history", label: t("menu.history") },
|
|
2436
|
-
{ value: "agent", label: `${color.ai("✦")} ${t("menu.agent")}`, hint:
|
|
3894
|
+
{ value: "agent", label: `${color.ai("✦")} ${t("menu.agent")}`, hint: (() => {
|
|
3895
|
+
const n = readInstalled().filter((a) => a.ready).length;
|
|
3896
|
+
return n ? t("menu.agentReady", { n }) : undefined;
|
|
3897
|
+
})() },
|
|
2437
3898
|
{ value: "autostart", label: t("menu.autostart"), hint: autostartEnabled() ? t("status.on") : t("status.off") },
|
|
2438
3899
|
{ value: "config", label: t("menu.config") },
|
|
2439
3900
|
{ value: "doctor", label: t("menu.doctor") },
|
|
@@ -2444,15 +3905,15 @@ async function menu(args) {
|
|
|
2444
3905
|
{ value: "exit", label: color.muted(t("menu.exit")) }
|
|
2445
3906
|
]
|
|
2446
3907
|
});
|
|
2447
|
-
if (
|
|
2448
|
-
|
|
3908
|
+
if (p3.isCancel(choice) || choice === "exit") {
|
|
3909
|
+
p3.outro(color.muted(t("menu.bye")));
|
|
2449
3910
|
return;
|
|
2450
3911
|
}
|
|
2451
3912
|
try {
|
|
2452
3913
|
switch (choice) {
|
|
2453
3914
|
case "start":
|
|
2454
3915
|
if (running) {
|
|
2455
|
-
|
|
3916
|
+
p3.log.warn(t("engine.running"));
|
|
2456
3917
|
break;
|
|
2457
3918
|
}
|
|
2458
3919
|
await start(args, { fromMenu: true });
|
|
@@ -2466,18 +3927,18 @@ async function menu(args) {
|
|
|
2466
3927
|
case "history": {
|
|
2467
3928
|
const items = history();
|
|
2468
3929
|
if (items.some((i) => i.file)) {
|
|
2469
|
-
const go = await
|
|
3930
|
+
const go = await p3.confirm({ message: t("history.openFolder"), initialValue: false });
|
|
2470
3931
|
if (go === true)
|
|
2471
3932
|
openFolder(renderDir());
|
|
2472
3933
|
}
|
|
2473
3934
|
break;
|
|
2474
3935
|
}
|
|
2475
3936
|
case "agent":
|
|
2476
|
-
|
|
3937
|
+
await agentMenu();
|
|
2477
3938
|
break;
|
|
2478
3939
|
case "autostart": {
|
|
2479
|
-
const on = await
|
|
2480
|
-
if (!
|
|
3940
|
+
const on = await p3.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
|
|
3941
|
+
if (!p3.isCancel(on))
|
|
2481
3942
|
autostart(on ? "on" : "off");
|
|
2482
3943
|
break;
|
|
2483
3944
|
}
|
|
@@ -2488,7 +3949,7 @@ async function menu(args) {
|
|
|
2488
3949
|
await doctor(args);
|
|
2489
3950
|
break;
|
|
2490
3951
|
case "clean": {
|
|
2491
|
-
const ok = await
|
|
3952
|
+
const ok = await p3.confirm({ message: t("clean.question"), initialValue: true });
|
|
2492
3953
|
if (ok === true)
|
|
2493
3954
|
await clean();
|
|
2494
3955
|
break;
|
|
@@ -2503,19 +3964,19 @@ async function menu(args) {
|
|
|
2503
3964
|
await login(args);
|
|
2504
3965
|
break;
|
|
2505
3966
|
case "logout": {
|
|
2506
|
-
const ok = await
|
|
3967
|
+
const ok = await p3.confirm({ message: t("confirm.logout"), initialValue: false });
|
|
2507
3968
|
if (ok === true)
|
|
2508
3969
|
logout();
|
|
2509
3970
|
break;
|
|
2510
3971
|
}
|
|
2511
3972
|
}
|
|
2512
3973
|
} catch (e) {
|
|
2513
|
-
|
|
3974
|
+
p3.log.error(`${icon.error} ${e.message}`);
|
|
2514
3975
|
}
|
|
2515
3976
|
}
|
|
2516
3977
|
}
|
|
2517
3978
|
|
|
2518
|
-
//
|
|
3979
|
+
// src/index.ts
|
|
2519
3980
|
function help() {
|
|
2520
3981
|
const rows = [
|
|
2521
3982
|
["start", t("help.start")],
|
|
@@ -2525,6 +3986,7 @@ function help() {
|
|
|
2525
3986
|
["open", t("help.open")],
|
|
2526
3987
|
["doctor", t("help.doctor")],
|
|
2527
3988
|
["bench", t("help.bench")],
|
|
3989
|
+
["agent list|add|login|remove", t("help.agent")],
|
|
2528
3990
|
["history", t("help.history")],
|
|
2529
3991
|
["autostart on|off", t("help.autostart")],
|
|
2530
3992
|
["config", t("help.config")],
|
|
@@ -2566,6 +4028,8 @@ var COMMANDS = {
|
|
|
2566
4028
|
process.exitCode = checks.some((c) => c.result === "error") ? 1 : 0;
|
|
2567
4029
|
},
|
|
2568
4030
|
bench: (a) => bench(a),
|
|
4031
|
+
agent: (a) => agentCommand(a),
|
|
4032
|
+
"mcp-bridge": () => runMcpBridge(),
|
|
2569
4033
|
history: () => history(),
|
|
2570
4034
|
autostart: (a) => autostart(a.rest[0]),
|
|
2571
4035
|
config: (a) => config(a),
|