hypeframe 0.2.0 → 0.5.0

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.
Files changed (3) hide show
  1. package/README.md +99 -40
  2. package/dist/index.js +1878 -275
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // packages/hypeframe/src/cli/args.ts
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
- // packages/hypeframe/src/config/account.ts
52
+ // src/config/account.ts
52
53
  import fs2 from "node:fs";
53
54
 
54
- // packages/hypeframe/src/config/paths.ts
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
- // packages/hypeframe/src/config/account.ts
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
- // packages/hypeframe/src/config/settings.ts
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
- // packages/hypeframe/src/ui/locale.ts
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";
@@ -167,6 +174,7 @@ var id = {
167
174
  "render.notYet": "Render di mesin ini belum bisa: {reason}. Mesin tetap tersambung; dicoba lagi 10 menit lagi.",
168
175
  "render.noH264": "Chrome {chrome} tidak bisa membuat video H.264",
169
176
  "render.downloading": "Mengunduh Chrome untuk render (sekali saja)",
177
+ "render.downloadingFfmpeg": "Mengunduh ffmpeg untuk render (sekali saja, ± 28 MB)",
170
178
  "render.job": "Render {kind} dimulai {size}",
171
179
  "render.jobDone": "Render selesai dalam {sec} ({size})",
172
180
  "render.jobFailed": "Render gagal: {reason}",
@@ -192,6 +200,33 @@ var id = {
192
200
  "menu.exit": "Keluar",
193
201
  "menu.bye": "Sampai jumpa.",
194
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.claudeKey": "Claude Code di HypeFrame memakai kunci API Anthropic (console.anthropic.com). Langganan Pro/Max hanya boleh dipakai di aplikasi Anthropic sendiri.",
217
+ "agent.askKey": "Tempel {name}",
218
+ "agent.removed": "{name} dilepas dari mesin ini.",
219
+ "agent.unknown": "Agen {id} tidak didukung. Pilihan: {list}",
220
+ "agent.notInstalledYet": "{name} belum dipasang. Jalankan: hypeframe agent add",
221
+ "agent.webHint": "Mengobrol dengan agen dilakukan di HypeFrame Web, halaman Asisten, selama mesin menyala.",
222
+ "agent.toolNoTab": "Agen memanggil alat HypeFrame, tapi tab HypeFrame Web tidak terbuka. Buka HypeFrame Web lalu kirim pesannya lagi.",
223
+ "agent.toolNoAnswer": "Agen memanggil alat HypeFrame, tapi HypeFrame Web tidak menjawab. Pastikan tabnya terbuka.",
224
+ "agent.keyFromShellAsk": "Pakai {name} yang sudah ada di terminal ini?",
225
+ "agent.keyFromShell": "Memakai {name} dari terminal ini (disimpan untuk agen ini saja).",
226
+ "agent.own": "{name} sudah terpasang di komputer ini ({path}); yang itu dipakai, tidak diunduh lagi.",
227
+ "agent.ownFailed": "Kalau {name} milikmu terlalu lama, pasang versi resmi: hypeframe agent add {id} --download",
228
+ "agent.ownTag": "punyamu sendiri",
229
+ "menu.agentReady": "{n} agen siap",
195
230
  "status.account": "Akun",
196
231
  "status.engine": "Mesin",
197
232
  "status.device": "Perangkat",
@@ -219,6 +254,7 @@ var id = {
219
254
  "doctor.free": "{size} kosong",
220
255
  "doctor.noFfmpeg": "ffmpeg tidak tersedia untuk sistem ini",
221
256
  "doctor.chromeLater": "belum ada; diunduh otomatis saat mesin menyala",
257
+ "doctor.ffmpegLater": "belum ada; diunduh otomatis saat mesin menyala",
222
258
  "doctor.alpha": "Klip transparan",
223
259
  "doctor.alphaNo": "tidak didukung Chrome ini; dibuat di server atau HP",
224
260
  "doctor.yes": "bisa",
@@ -241,7 +277,7 @@ var id = {
241
277
  "autostart.off": "Nyala otomatis dimatikan.",
242
278
  "autostart.isOn": "Nyala otomatis: nyala.",
243
279
  "autostart.isOff": "Nyala otomatis: mati.",
244
- "autostart.needGlobal": "Nyala otomatis butuh hypeframe yang terpasang tetap, bukan salinan sementara npx.",
280
+ "autostart.needGlobal": "Nyala otomatis butuh hypeframe yang terpasang tetap (pemasang curl atau npm i -g), bukan salinan sementara npx.",
245
281
  "autostart.needLogin": "Sambungkan perangkat ke akun dulu (hypeframe login).",
246
282
  "clean.question": "Hapus Chrome unduhan, cache halaman render, log lama, dan render yang gagal? Video yang sudah jadi tetap disimpan.",
247
283
  "clean.running": "Matikan mesin dulu sebelum membersihkan.",
@@ -251,6 +287,7 @@ var id = {
251
287
  "update.running": "Memperbarui hypeframe...",
252
288
  "update.done": "hypeframe sudah versi terbaru.",
253
289
  "update.failed": "Pembaruan gagal. Coba jalankan sendiri: npm i -g hypeframe@latest",
290
+ "update.failedStandalone": "Pembaruan gagal. Coba jalankan pemasang lagi: curl -fsSL https://hype-frame.com/install | bash",
254
291
  "update.npx": "Kamu menjalankan hypeframe lewat npx; versi terbaru dipakai dengan:",
255
292
  "open.done": "Membuka {web}",
256
293
  "help.usage": "Pakai",
@@ -265,6 +302,7 @@ var id = {
265
302
  "help.open": "buka HypeFrame Web di browser",
266
303
  "help.doctor": "periksa Node, Chrome, ffmpeg, koneksi, ruang disk",
267
304
  "help.bench": "ukur kecepatan render 720p dan 1080p",
305
+ "help.agent": "pasang dan masuk akun agen AI (Claude Code, Antigravity, Codex, OpenCode)",
268
306
  "help.history": "render 24 jam terakhir",
269
307
  "help.autostart": "nyalakan mesin saat masuk ke komputer",
270
308
  "help.config": "nama perangkat, GPU, bahasa",
@@ -304,6 +342,7 @@ var en = {
304
342
  "render.notYet": "Rendering is not available yet: {reason}. The engine stays connected; retrying in 10 minutes.",
305
343
  "render.noH264": "Chrome {chrome} cannot encode H.264 video",
306
344
  "render.downloading": "Downloading Chrome for rendering (one time)",
345
+ "render.downloadingFfmpeg": "Downloading ffmpeg for rendering (one time, about 28 MB)",
307
346
  "render.job": "Rendering {kind} {size}",
308
347
  "render.jobDone": "Render finished in {sec} ({size})",
309
348
  "render.jobFailed": "Render failed: {reason}",
@@ -329,6 +368,33 @@ var en = {
329
368
  "menu.exit": "Exit",
330
369
  "menu.bye": "See you.",
331
370
  "agent.soon": "An AI assistant that works right on your device is on the way.",
371
+ "agent.menuQuestion": "Pick an agent. Install and log in once here, then chat from HypeFrame Web.",
372
+ "agent.ready": "ready to use from the web",
373
+ "agent.needLogin": "needs login",
374
+ "agent.notInstalled": "not installed",
375
+ "agent.add": "Install and log in",
376
+ "agent.login": "Log in again",
377
+ "agent.remove": "Remove from this machine",
378
+ "agent.back": "Back",
379
+ "agent.installing": "Installing {name} from the official ACP registry...",
380
+ "agent.installed": "{name} {version} installed.",
381
+ "agent.loggingIn": "Logging in to {name}...",
382
+ "agent.loggedIn": "{name} is ready. Open HypeFrame Web and pick {name} in the Assistant (the engine must be running).",
383
+ "agent.loginFailed": "{name} is not usable yet: the login did not succeed. Try again from the AI assistant menu.",
384
+ "agent.claudeKey": "Claude Code in HypeFrame uses an Anthropic API key (console.anthropic.com). Pro/Max subscriptions may only be used in Anthropic’s own apps.",
385
+ "agent.askKey": "Paste {name}",
386
+ "agent.removed": "{name} removed from this machine.",
387
+ "agent.unknown": "Agent {id} is not supported. Choices: {list}",
388
+ "agent.notInstalledYet": "{name} is not installed. Run: hypeframe agent add",
389
+ "agent.webHint": "Chatting with agents happens in HypeFrame Web, on the Assistant page, while the engine runs.",
390
+ "agent.toolNoTab": "An agent called a HypeFrame tool, but no HypeFrame Web tab is open. Open HypeFrame Web and send the message again.",
391
+ "agent.toolNoAnswer": "An agent called a HypeFrame tool, but HypeFrame Web did not answer. Make sure its tab is open.",
392
+ "agent.keyFromShellAsk": "Use the {name} already set in this terminal?",
393
+ "agent.keyFromShell": "Using {name} from this terminal (saved for this agent only).",
394
+ "agent.own": "{name} is already installed on this computer ({path}); that copy is used, nothing is downloaded.",
395
+ "agent.ownFailed": "If your own {name} is too old, install the official one: hypeframe agent add {id} --download",
396
+ "agent.ownTag": "your own copy",
397
+ "menu.agentReady": "{n} agents ready",
332
398
  "status.account": "Account",
333
399
  "status.engine": "Engine",
334
400
  "status.device": "Device",
@@ -356,6 +422,7 @@ var en = {
356
422
  "doctor.free": "{size} free",
357
423
  "doctor.noFfmpeg": "ffmpeg is not available for this system",
358
424
  "doctor.chromeLater": "not yet; downloaded automatically when the engine starts",
425
+ "doctor.ffmpegLater": "not yet; downloaded automatically when the engine starts",
359
426
  "doctor.alpha": "Transparent clips",
360
427
  "doctor.alphaNo": "not supported by this Chrome; made on the server or phone",
361
428
  "doctor.yes": "yes",
@@ -378,7 +445,7 @@ var en = {
378
445
  "autostart.off": "Autostart off.",
379
446
  "autostart.isOn": "Autostart: on.",
380
447
  "autostart.isOff": "Autostart: off.",
381
- "autostart.needGlobal": "Autostart needs an installed hypeframe, not the temporary npx copy.",
448
+ "autostart.needGlobal": "Autostart needs an installed hypeframe (the curl installer or npm i -g), not the temporary npx copy.",
382
449
  "autostart.needLogin": "Connect this device to an account first (hypeframe login).",
383
450
  "clean.question": "Delete the downloaded Chrome, cached render pages, old logs and failed renders? Finished videos are kept.",
384
451
  "clean.running": "Stop the engine before cleaning up.",
@@ -388,6 +455,7 @@ var en = {
388
455
  "update.running": "Updating hypeframe...",
389
456
  "update.done": "hypeframe is up to date.",
390
457
  "update.failed": "Update failed. Try it yourself: npm i -g hypeframe@latest",
458
+ "update.failedStandalone": "Update failed. Run the installer again: curl -fsSL https://hype-frame.com/install | bash",
391
459
  "update.npx": "You are running hypeframe through npx; the latest version runs with:",
392
460
  "open.done": "Opening {web}",
393
461
  "help.usage": "Usage",
@@ -402,6 +470,7 @@ var en = {
402
470
  "help.open": "open HypeFrame Web in the browser",
403
471
  "help.doctor": "check Node, Chrome, ffmpeg, network, disk space",
404
472
  "help.bench": "measure render speed at 720p and 1080p",
473
+ "help.agent": "install and log in AI agents (Claude Code, Antigravity, Codex, OpenCode)",
405
474
  "help.history": "renders from the last 24 hours",
406
475
  "help.autostart": "start the engine when you sign in",
407
476
  "help.config": "device name, GPU, language",
@@ -419,11 +488,11 @@ function t(key, vars = {}) {
419
488
  return s.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? `{${k}}`));
420
489
  }
421
490
 
422
- // packages/hypeframe/src/ui/log.ts
491
+ // src/ui/log.ts
423
492
  import fs4 from "node:fs";
424
493
  import path2 from "node:path";
425
494
 
426
- // packages/hypeframe/src/ui/theme.ts
495
+ // src/ui/theme.ts
427
496
  import picocolors from "picocolors";
428
497
  var env = process.env;
429
498
  var enabled = !("NO_COLOR" in env) && env.TERM !== "dumb" && ("FORCE_COLOR" in env ? env.FORCE_COLOR !== "0" : !!process.stdout.isTTY);
@@ -457,7 +526,7 @@ var icon = {
457
526
  };
458
527
  var plain = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
459
528
 
460
- // packages/hypeframe/src/ui/log.ts
529
+ // src/ui/log.ts
461
530
  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;
462
531
  var mask = (s) => s.replace(SECRET, (m) => `${m.slice(0, 4)}…`);
463
532
  var MAX_FILE = 1024 * 1024;
@@ -495,13 +564,12 @@ var log = {
495
564
  detail: (m) => write("detail", m)
496
565
  };
497
566
 
498
- // packages/hypeframe/src/cli/commands/start.ts
499
- import crypto3 from "node:crypto";
500
- import ffmpegPath from "ffmpeg-static";
567
+ // src/cli/commands/start.ts
568
+ import crypto7 from "node:crypto";
501
569
 
502
- // packages/protocol/src/index.ts
570
+ // ../protocol/src/index.ts
503
571
  var PROTOCOL_VERSION = 1;
504
- var ALLOWED_KINDS = ["status", "kunci"];
572
+ var ALLOWED_KINDS = ["status", "kunci", "agen.mulai", "agen.kirim", "agen.izin", "agen.batal", "agen.opsi", "agen.riwayat"];
505
573
  var CloseCode = {
506
574
  BadHello: 4001,
507
575
  Replaced: 4002,
@@ -522,8 +590,1050 @@ var EngineError = {
522
590
  BadPackage: "Paket berisi berkas yang tidak diizinkan."
523
591
  };
524
592
 
525
- // packages/hypeframe/src/config/lock.ts
593
+ // src/agent/service.ts
594
+ import crypto2 from "node:crypto";
595
+ import fs8 from "node:fs";
596
+ import path5 from "node:path";
597
+ // package.json
598
+ var package_default = {
599
+ name: "hypeframe",
600
+ version: "0.5.0",
601
+ description: "Local engine for HypeFrame Web: code clips, video renders and AI agents run on your own machine; the web is just the view.",
602
+ keywords: [
603
+ "hypeframe",
604
+ "video",
605
+ "render",
606
+ "motion-graphics",
607
+ "chrome-headless",
608
+ "cli"
609
+ ],
610
+ homepage: "https://hype-frame.com",
611
+ repository: {
612
+ type: "git",
613
+ url: "git+https://github.com/sairidev/hypeframe.git",
614
+ directory: "packages/hypeframe"
615
+ },
616
+ bugs: {
617
+ url: "https://github.com/sairidev/hypeframe/issues"
618
+ },
619
+ author: "SairiDev",
620
+ license: "MIT",
621
+ type: "module",
622
+ bin: {
623
+ hypeframe: "bin/hypeframe.js"
624
+ },
625
+ files: [
626
+ "bin",
627
+ "dist",
628
+ "README.md",
629
+ "LICENSE"
630
+ ],
631
+ engines: {
632
+ node: ">=20.3"
633
+ },
634
+ scripts: {
635
+ build: "bun run ../../script/build.ts",
636
+ typecheck: "tsc --noEmit",
637
+ test: "node --import tsx --test test/*.test.ts"
638
+ },
639
+ dependencies: {
640
+ "@clack/prompts": "1.9.0",
641
+ "@puppeteer/browsers": "2.6.1",
642
+ "ffmpeg-static": "5.2.0",
643
+ picocolors: "1.1.1",
644
+ "puppeteer-core": "23.11.1",
645
+ ws: "8.18.0",
646
+ yauzl: "3.2.0"
647
+ }
648
+ };
649
+
650
+ // src/config/version.ts
651
+ var VERSION = process.env.HF_MESIN_VERSI || package_default.version;
652
+
653
+ // src/agent/instructions.ts
654
+ 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.";
655
+ var AGENTS_MD = `# HypeFrame
656
+
657
+ 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.
658
+
659
+ - 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).
660
+ - ${MCP_INSTRUCTIONS}
661
+ - The user is usually not a programmer. Reply in their language (most write Indonesian), short and plain, without technical words.
662
+ - When create_motion or create_audio waits for approval (the tool result says so), tell the user to check the editor in HypeFrame Web.
663
+ - 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>).
664
+ `;
665
+
666
+ // src/agent/registry.ts
667
+ import { spawnSync } from "node:child_process";
526
668
  import fs5 from "node:fs";
669
+ var SUPPORTED_AGENTS = ["claude-acp", "antigravity-acp", "codex-acp", "opencode"];
670
+ var isSupported = (id) => SUPPORTED_AGENTS.includes(id);
671
+ var OFFICIAL_REGISTRY = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
672
+ var registryUrl = () => process.env.HYPEFRAME_ACP_REGISTRY || OFFICIAL_REGISTRY;
673
+ var isLocalRegistry = (u) => u.startsWith("file:") || /^http:\/\/127\.0\.0\.1[:/]/.test(u);
674
+ function isMusl() {
675
+ if (fs5.existsSync("/etc/alpine-release"))
676
+ return true;
677
+ const r = spawnSync("ldd", ["--version"], { encoding: "utf8" });
678
+ return /musl/i.test(`${r.stdout ?? ""}${r.stderr ?? ""}`);
679
+ }
680
+ function platformKey() {
681
+ const os = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "darwin" : "linux";
682
+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
683
+ return `${os}-${arch}${os === "linux" && isMusl() ? "-musl" : ""}`;
684
+ }
685
+ var ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
686
+ function valid(a) {
687
+ const x = a;
688
+ return !!x && typeof x.id === "string" && ID.test(x.id) && typeof x.name === "string" && typeof x.version === "string" && !!x.distribution && typeof x.distribution === "object";
689
+ }
690
+ async function fetchRegistry() {
691
+ const u = registryUrl();
692
+ const text = u.startsWith("file:") ? fs5.readFileSync(new URL(u), "utf8") : await (await fetch(u, { signal: AbortSignal.timeout(20000) })).text();
693
+ const j = JSON.parse(text);
694
+ const local = isLocalRegistry(u);
695
+ return (Array.isArray(j.agents) ? j.agents : []).filter(valid).map((a) => local ? a : { ...a, distribution: { ...a.distribution, local: undefined } });
696
+ }
697
+
698
+ // src/agent/session.ts
699
+ import crypto from "node:crypto";
700
+ import fs6 from "node:fs";
701
+ import path3 from "node:path";
702
+
703
+ // src/agent/acp.ts
704
+ import { spawn } from "node:child_process";
705
+ import { EventEmitter } from "node:events";
706
+ import readline from "node:readline";
707
+ class RpcError extends Error {
708
+ code;
709
+ data;
710
+ constructor(code, message, data) {
711
+ super(message);
712
+ this.code = code;
713
+ this.data = data;
714
+ }
715
+ }
716
+
717
+ class AcpProcess extends EventEmitter {
718
+ child;
719
+ nextId = 1;
720
+ pending = new Map;
721
+ stderrTail = "";
722
+ onRequest = async (method) => {
723
+ throw new RpcError(-32601, `Method not found: ${method}`);
724
+ };
725
+ onNotification = () => {
726
+ return;
727
+ };
728
+ get alive() {
729
+ return !!this.child && this.child.exitCode === null && !this.child.killed;
730
+ }
731
+ get stderr() {
732
+ return this.stderrTail;
733
+ }
734
+ async start(agent, cwd, env = {}, timeoutMs = 180000) {
735
+ const child = spawn(agent.launch.cmd, agent.launch.args, { cwd, env: { ...process.env, ...agent.launch.env, ...env }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
736
+ this.child = child;
737
+ child.stderr?.on("data", (d) => this.stderrTail = (this.stderrTail + d).slice(-4096));
738
+ child.stdin?.on("error", () => {
739
+ return;
740
+ });
741
+ readline.createInterface({ input: child.stdout }).on("line", (line) => this.receive(line));
742
+ child.on("error", (e) => this.finish(e));
743
+ child.on("exit", (code) => this.finish(null, code));
744
+ return this.request("initialize", {
745
+ protocolVersion: 1,
746
+ clientCapabilities: { auth: { terminal: true }, fs: { readTextFile: true, writeTextFile: true }, terminal: false },
747
+ clientInfo: { name: "hypeframe", title: "HypeFrame", version: VERSION }
748
+ }, timeoutMs);
749
+ }
750
+ exited = false;
751
+ finish(err, code = null) {
752
+ if (this.exited)
753
+ return;
754
+ this.exited = true;
755
+ const e = err ?? new Error(`Agent stopped (exit ${code})`);
756
+ for (const p of this.pending.values())
757
+ p.fail(e);
758
+ this.pending.clear();
759
+ this.emit("exit", err ? -1 : code);
760
+ }
761
+ send(m) {
762
+ if (this.child?.stdin?.writable)
763
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}
764
+ `);
765
+ }
766
+ request(method, params, timeoutMs) {
767
+ if (this.exited)
768
+ return Promise.reject(new Error("Agent stopped"));
769
+ const id = this.nextId++;
770
+ return new Promise((ok, fail) => {
771
+ let timer;
772
+ const done = (f) => (v) => (clearTimeout(timer), f(v));
773
+ this.pending.set(id, { ok: done(ok), fail: done(fail) });
774
+ if (timeoutMs)
775
+ timer = setTimeout(() => {
776
+ if (!this.pending.delete(id))
777
+ return;
778
+ fail(new Error(`${method} took longer than ${Math.round(timeoutMs / 1000)} s`));
779
+ }, timeoutMs);
780
+ this.send({ id, method, params });
781
+ });
782
+ }
783
+ notify(method, params) {
784
+ this.send({ method, params });
785
+ }
786
+ receive(line) {
787
+ let m;
788
+ try {
789
+ m = JSON.parse(line);
790
+ } catch {
791
+ return;
792
+ }
793
+ if (!m || typeof m !== "object")
794
+ return;
795
+ if (m.method === undefined && m.id !== undefined) {
796
+ const p = this.pending.get(m.id);
797
+ if (!p)
798
+ return;
799
+ this.pending.delete(m.id);
800
+ if (m.error)
801
+ p.fail(new RpcError(Number(m.error.code) || -32000, String(m.error.message || "error"), m.error.data));
802
+ else
803
+ p.ok(m.result);
804
+ return;
805
+ }
806
+ if (typeof m.method !== "string")
807
+ return;
808
+ if (m.id === undefined || m.id === null)
809
+ return this.onNotification(m.method, m.params);
810
+ 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) } }));
811
+ }
812
+ stop() {
813
+ if (!this.child || this.exited)
814
+ return Promise.resolve();
815
+ return new Promise((ok) => {
816
+ const t = setTimeout(ok, 3000);
817
+ this.once("exit", () => (clearTimeout(t), ok()));
818
+ const pid = this.child?.pid;
819
+ if (process.platform === "win32" && pid) {
820
+ const k = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
821
+ k.on("error", () => this.child?.kill());
822
+ } else
823
+ this.child?.kill();
824
+ });
825
+ }
826
+ }
827
+
828
+ // src/agent/session.ts
829
+ var UNSAFE_MODE = /bypass|dont.?ask|accept.?edits|yolo|full.?access|danger/i;
830
+ var SAFE_MODES = ["default", "ask"];
831
+ var MAX_READ = 10 * 1024 * 1024;
832
+ var MAX_OPTIONS = 48 * 1024;
833
+ var isModeOption = (c) => !!c && (c.category === "mode" || /mode/i.test(String(c.id ?? "")));
834
+ 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);
835
+ function safeOptions(raw) {
836
+ const out = {};
837
+ if (Array.isArray(raw?.models?.availableModels) && raw.models.availableModels.length)
838
+ out.models = raw.models;
839
+ if (Array.isArray(raw?.modes?.availableModes) && raw.modes.availableModes.length)
840
+ out.modes = { ...raw.modes, availableModes: raw.modes.availableModes.filter((m) => !UNSAFE_MODE.test(String(m?.id ?? ""))) };
841
+ if (Array.isArray(raw?.configOptions))
842
+ out.configOptions = safeConfig(raw.configOptions);
843
+ return Buffer.byteLength(JSON.stringify(out)) > MAX_OPTIONS ? {} : out;
844
+ }
845
+ function splitId(id) {
846
+ const i = id.indexOf("/");
847
+ return i > 0 ? [id.slice(0, i), id.slice(i + 1)] : ["", id];
848
+ }
849
+ var lexists = (p) => {
850
+ try {
851
+ fs6.lstatSync(p);
852
+ return true;
853
+ } catch {
854
+ return false;
855
+ }
856
+ };
857
+ function insideFolder(folder, p) {
858
+ if (typeof p !== "string" || !p)
859
+ return false;
860
+ const abs = path3.resolve(folder, p);
861
+ const rel = path3.relative(folder, abs);
862
+ if (rel.startsWith("..") || path3.isAbsolute(rel))
863
+ return false;
864
+ let probe = abs;
865
+ while (!lexists(probe) && path3.dirname(probe) !== probe)
866
+ probe = path3.dirname(probe);
867
+ try {
868
+ const r = path3.relative(fs6.realpathSync(folder), fs6.realpathSync(probe));
869
+ return !(r.startsWith("..") || path3.isAbsolute(r));
870
+ } catch {
871
+ return false;
872
+ }
873
+ }
874
+ var OUTSIDE = "Path outside the HypeFrame project folder";
875
+
876
+ class AgentSessions {
877
+ o;
878
+ procs = new Map;
879
+ starting = new Map;
880
+ sessions = new Map;
881
+ prompting = new Set;
882
+ constructor(o) {
883
+ this.o = o;
884
+ }
885
+ running() {
886
+ return [...this.procs.keys()];
887
+ }
888
+ process(agentId) {
889
+ const ada = this.procs.get(agentId);
890
+ if (ada?.proc.alive)
891
+ return Promise.resolve(ada);
892
+ const busy = this.starting.get(agentId);
893
+ if (busy)
894
+ return busy;
895
+ const agent = this.o.agent(agentId);
896
+ if (!agent)
897
+ return Promise.reject(new Error(`Agent ${agentId} is not installed`));
898
+ const proc = new AcpProcess;
899
+ proc.onRequest = (m, p) => this.fromAgent(agentId, m, p);
900
+ proc.onNotification = (m, p) => {
901
+ if (m === "session/update")
902
+ this.queue(`${agentId}/${String(p?.sessionId ?? "")}`, p?.update);
903
+ };
904
+ proc.on("exit", (code) => {
905
+ if (this.procs.get(agentId)?.proc === proc)
906
+ this.procs.delete(agentId);
907
+ for (const [id, s] of this.sessions)
908
+ if (s.agentId === agentId) {
909
+ this.flush(id);
910
+ this.sessions.delete(id);
911
+ }
912
+ this.o.onExit(agentId, code);
913
+ });
914
+ const cwd = path3.join(agentDir(), agentId, "kerja");
915
+ fs6.mkdirSync(cwd, { recursive: true });
916
+ const p = proc.start(agent, cwd, this.o.env?.(agentId) ?? {}, this.o.startTimeoutMs ?? 180000).then((init) => {
917
+ const entry = { proc, init };
918
+ this.procs.set(agentId, entry);
919
+ return entry;
920
+ }).catch(async (e) => {
921
+ await proc.stop();
922
+ throw e;
923
+ }).finally(() => this.starting.delete(agentId));
924
+ this.starting.set(agentId, p);
925
+ return p;
926
+ }
927
+ async open({ agentId, projectId, resumeId }) {
928
+ const { proc, init } = await this.process(agentId);
929
+ const [resumeAgent, resumeOwn] = resumeId ? splitId(resumeId) : ["", ""];
930
+ const resume = resumeOwn && (!resumeAgent || resumeAgent === agentId) ? resumeOwn : "";
931
+ const key = (own) => `${agentId}/${own}`;
932
+ const live = resume ? this.sessions.get(key(resume)) : undefined;
933
+ if (live)
934
+ return { sessionId: key(resume), init, raw: {}, dimuat: "hidup", routeId: live.routeId, opsi: live.opsi ?? {} };
935
+ const cwd = projectDir(projectId);
936
+ fs6.writeFileSync(path3.join(cwd, "AGENTS.md"), AGENTS_MD);
937
+ const routeId = crypto.randomBytes(9).toString("base64url");
938
+ const params = { cwd, mcpServers: this.o.mcpServers(cwd, projectId, routeId) };
939
+ const limit = this.o.sessionTimeoutMs ?? 90000;
940
+ let raw;
941
+ let dimuat = "baru";
942
+ if (resume && init.agentCapabilities?.loadSession) {
943
+ const s = { agentId, id: resume, cwd, routeId, buffer: [], loading: true };
944
+ this.sessions.set(key(resume), s);
945
+ try {
946
+ raw = { ...await proc.request("session/load", { ...params, sessionId: resume }, limit) ?? {}, sessionId: resume };
947
+ dimuat = "load";
948
+ this.flush(key(resume));
949
+ s.loading = false;
950
+ } catch {
951
+ this.sessions.delete(key(resume));
952
+ raw = undefined;
953
+ }
954
+ }
955
+ try {
956
+ raw ??= await proc.request("session/new", params, limit);
957
+ } catch (e) {
958
+ if (/took longer/.test(e.message))
959
+ await proc.stop();
960
+ throw e;
961
+ }
962
+ const own = String(raw?.sessionId ?? "");
963
+ if (!own)
964
+ throw new Error("The agent did not create a session");
965
+ let s = this.sessions.get(key(own));
966
+ if (!s)
967
+ this.sessions.set(key(own), s = { agentId, id: own, cwd, routeId, buffer: [] });
968
+ const opsi = safeOptions(raw);
969
+ const mode = await this.safeMode(proc, own, raw);
970
+ if (mode && opsi.modes)
971
+ opsi.modes = { ...opsi.modes, currentModeId: mode };
972
+ s.opsi = opsi;
973
+ return { sessionId: key(own), init, raw, dimuat, routeId, opsi };
974
+ }
975
+ async safeMode(proc, own, raw) {
976
+ const current = String(raw?.modes?.currentModeId ?? "");
977
+ const available = Array.isArray(raw?.modes?.availableModes) ? raw.modes.availableModes.map((m) => String(m?.id ?? "")) : [];
978
+ let switched;
979
+ if (current && UNSAFE_MODE.test(current)) {
980
+ const target = SAFE_MODES.find((m) => available.includes(m));
981
+ if (target && await proc.request("session/set_mode", { sessionId: own, modeId: target }, 15000).then(() => true, () => false))
982
+ switched = target;
983
+ }
984
+ for (const c of Array.isArray(raw?.configOptions) ? raw.configOptions : []) {
985
+ if (!isModeOption(c) || !UNSAFE_MODE.test(String(c.currentValue ?? "")))
986
+ continue;
987
+ const values = (c.options ?? []).map((o) => String(o?.value ?? ""));
988
+ const target = SAFE_MODES.find((m) => values.includes(m));
989
+ if (target)
990
+ await proc.request("session/set_config_option", { sessionId: own, configId: String(c.id), value: target }, 15000).catch(() => {
991
+ return;
992
+ });
993
+ }
994
+ return switched;
995
+ }
996
+ async setOption(sessionId, o) {
997
+ const s = this.sessions.get(sessionId);
998
+ if (!s)
999
+ throw new Error("Unknown session");
1000
+ const e = this.procs.get(s.agentId);
1001
+ if (!e)
1002
+ throw new Error("Agent stopped");
1003
+ const id = String(o.id ?? "").slice(0, 100);
1004
+ const value = String(o.nilai ?? "").slice(0, 200);
1005
+ const config = s.opsi?.configOptions?.find((c) => c.id === id);
1006
+ const modeLike = o.jenis === "mode" || o.jenis !== "model" && (isModeOption(config) || /mode/i.test(id));
1007
+ if (modeLike && UNSAFE_MODE.test(value))
1008
+ throw new Error("A mode that skips asking is not allowed in HypeFrame");
1009
+ if (o.jenis === "model")
1010
+ return await e.proc.request("session/set_model", { sessionId: s.id, modelId: value }, 15000), {};
1011
+ if (o.jenis === "mode")
1012
+ return await e.proc.request("session/set_mode", { sessionId: s.id, modeId: value }, 15000), {};
1013
+ const r = await e.proc.request("session/set_config_option", { sessionId: s.id, configId: id, value }, 15000);
1014
+ if (!Array.isArray(r?.configOptions))
1015
+ return {};
1016
+ const configOptions = safeConfig(r.configOptions);
1017
+ s.opsi = { ...s.opsi, configOptions };
1018
+ return { configOptions };
1019
+ }
1020
+ agentOf(sessionId) {
1021
+ return this.sessions.get(sessionId)?.agentId ?? null;
1022
+ }
1023
+ busy(sessionId) {
1024
+ return this.prompting.has(sessionId);
1025
+ }
1026
+ async prompt(sessionId, text) {
1027
+ const s = this.sessions.get(sessionId);
1028
+ if (!s)
1029
+ throw new Error("Unknown session");
1030
+ const e = this.procs.get(s.agentId);
1031
+ if (!e)
1032
+ throw new Error("Agent stopped");
1033
+ this.prompting.add(sessionId);
1034
+ try {
1035
+ return await e.proc.request("session/prompt", { sessionId: s.id, prompt: [{ type: "text", text }] });
1036
+ } finally {
1037
+ this.prompting.delete(sessionId);
1038
+ this.flush(sessionId);
1039
+ }
1040
+ }
1041
+ cancel(sessionId) {
1042
+ const s = this.sessions.get(sessionId);
1043
+ if (s)
1044
+ this.procs.get(s.agentId)?.proc.notify("session/cancel", { sessionId: s.id });
1045
+ }
1046
+ async stopAll() {
1047
+ await Promise.all([...this.procs.values()].map(({ proc }) => proc.stop()));
1048
+ }
1049
+ queue(sessionId, update) {
1050
+ const s = this.sessions.get(sessionId);
1051
+ if (!s || update === undefined)
1052
+ return;
1053
+ s.buffer.push(update);
1054
+ s.timer ??= setTimeout(() => this.flush(sessionId), this.o.flushMs ?? 100);
1055
+ }
1056
+ flush(sessionId) {
1057
+ const s = this.sessions.get(sessionId);
1058
+ if (!s)
1059
+ return;
1060
+ clearTimeout(s.timer);
1061
+ s.timer = undefined;
1062
+ if (s.buffer.length)
1063
+ this.o.onUpdate(sessionId, s.buffer.splice(0), { replay: !!s.loading });
1064
+ }
1065
+ async fromAgent(agentId, method, raw) {
1066
+ const key = `${agentId}/${String(raw?.sessionId ?? "")}`;
1067
+ const s = this.sessions.get(key);
1068
+ if (!s)
1069
+ throw new RpcError(-32602, "Unknown session");
1070
+ const p = { ...raw, sessionId: key };
1071
+ if (method === "session/request_permission") {
1072
+ const options = Array.isArray(p.options) ? p.options : [];
1073
+ const reject = options.find((o) => String(o.kind).startsWith("reject"));
1074
+ const refuse = () => reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
1075
+ const locations = Array.isArray(p.toolCall?.locations) ? p.toolCall.locations : [];
1076
+ if (locations.some((l) => !insideFolder(s.cwd, l?.path)))
1077
+ return refuse();
1078
+ this.flush(String(p.sessionId));
1079
+ let timer;
1080
+ const choice = await Promise.race([
1081
+ this.o.onPermission(String(p.sessionId), { sessionId: String(p.sessionId), toolCall: p.toolCall ?? {}, options }, { mustAsk: locations.length === 0 }),
1082
+ new Promise((ok) => timer = setTimeout(() => ok(null), this.o.permissionTimeoutMs ?? 5 * 60000))
1083
+ ]).finally(() => clearTimeout(timer));
1084
+ return choice && options.some((o) => o.optionId === choice) ? { outcome: { outcome: "selected", optionId: choice } } : refuse();
1085
+ }
1086
+ if (method === "fs/read_text_file") {
1087
+ if (!insideFolder(s.cwd, p.path))
1088
+ throw new RpcError(-32602, OUTSIDE);
1089
+ const st = fs6.statSync(path3.resolve(s.cwd, p.path), { throwIfNoEntry: false });
1090
+ if (!st?.isFile())
1091
+ throw new RpcError(-32602, "Not a regular file");
1092
+ if (st.size > MAX_READ)
1093
+ throw new RpcError(-32602, "File too large (over 10 MB)");
1094
+ let content = fs6.readFileSync(path3.resolve(s.cwd, p.path), "utf8");
1095
+ if (p.line || p.limit) {
1096
+ const lines = content.split(`
1097
+ `);
1098
+ const from = Math.max(0, (Number(p.line) || 1) - 1);
1099
+ content = lines.slice(from, p.limit ? from + Number(p.limit) : undefined).join(`
1100
+ `);
1101
+ }
1102
+ return { content };
1103
+ }
1104
+ if (method === "fs/write_text_file") {
1105
+ if (!insideFolder(s.cwd, p.path))
1106
+ throw new RpcError(-32602, OUTSIDE);
1107
+ const f = path3.resolve(s.cwd, p.path);
1108
+ fs6.mkdirSync(path3.dirname(f), { recursive: true });
1109
+ fs6.writeFileSync(f, String(p.content ?? ""));
1110
+ return null;
1111
+ }
1112
+ throw new RpcError(-32601, `Method not found: ${method}`);
1113
+ }
1114
+ }
1115
+
1116
+ // src/agent/store.ts
1117
+ import fs7 from "node:fs";
1118
+ import path4 from "node:path";
1119
+ function setReady(id, ready) {
1120
+ const a = readInstalled().find((x) => x.id === id);
1121
+ if (a)
1122
+ writeInstalled({ ...a, ready });
1123
+ }
1124
+ var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
1125
+ var folder = (id) => {
1126
+ if (typeof id !== "string" || !AGENT_ID.test(id))
1127
+ throw new Error(`Invalid agent id: ${JSON.stringify(String(id)).slice(0, 60)}`);
1128
+ return path4.join(agentDir(), id);
1129
+ };
1130
+ function readInstalled() {
1131
+ const out = [];
1132
+ for (const id of fs7.readdirSync(agentDir())) {
1133
+ if (!AGENT_ID.test(id))
1134
+ continue;
1135
+ try {
1136
+ const a = JSON.parse(fs7.readFileSync(path4.join(folder(id), "agent.json"), "utf8"));
1137
+ if (a.id === id && a.launch?.cmd)
1138
+ out.push(a);
1139
+ } catch {}
1140
+ }
1141
+ return out;
1142
+ }
1143
+ function writeInstalled(a) {
1144
+ fs7.mkdirSync(folder(a.id), { recursive: true });
1145
+ const f = path4.join(folder(a.id), "agent.json");
1146
+ fs7.writeFileSync(`${f}.tmp`, JSON.stringify(a, null, 2));
1147
+ fs7.renameSync(`${f}.tmp`, f);
1148
+ }
1149
+ function removeAgent(id) {
1150
+ fs7.rmSync(folder(id), { recursive: true, force: true });
1151
+ }
1152
+ function agentEnv(id) {
1153
+ try {
1154
+ return JSON.parse(fs7.readFileSync(path4.join(folder(id), "env.json"), "utf8"));
1155
+ } catch {
1156
+ return {};
1157
+ }
1158
+ }
1159
+ function saveAgentEnv(id, env) {
1160
+ fs7.mkdirSync(folder(id), { recursive: true });
1161
+ const f = path4.join(folder(id), "env.json");
1162
+ fs7.writeFileSync(`${f}.tmp`, JSON.stringify({ ...agentEnv(id), ...env }), { mode: 384 });
1163
+ fs7.renameSync(`${f}.tmp`, f);
1164
+ }
1165
+
1166
+ // src/agent/service.ts
1167
+ var MAX_NEWS = 180 * 1024;
1168
+ var MAX_TOOL_ARGS = 200 * 1024;
1169
+ var MAX_TEXT = 48 * 1024;
1170
+ 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.";
1171
+ var ERRORS = {
1172
+ tab: NOT_OPEN,
1173
+ terputus: "The HypeFrame engine is offline right now. Try again in a moment.",
1174
+ waktu: "HypeFrame Web did not answer in time. Make sure the HypeFrame Web tab is open, then try again."
1175
+ };
1176
+ var MAX_HISTORY = 2 * 1024 * 1024;
1177
+ var HISTORY_ANSWER = 170 * 1024;
1178
+ var MAX_FILE2 = 4 * 1024 * 1024;
1179
+ var PIECE = 150 * 1024;
1180
+ var MEDIA = {
1181
+ png: "image/png",
1182
+ jpg: "image/jpeg",
1183
+ jpeg: "image/jpeg",
1184
+ webp: "image/webp",
1185
+ gif: "image/gif",
1186
+ svg: "image/svg+xml",
1187
+ mp3: "audio/mpeg",
1188
+ wav: "audio/wav",
1189
+ ogg: "audio/ogg",
1190
+ m4a: "audio/mp4",
1191
+ aac: "audio/aac",
1192
+ mp4: "video/mp4",
1193
+ webm: "video/webm",
1194
+ mov: "video/quicktime",
1195
+ json: "application/json",
1196
+ lottie: "application/zip",
1197
+ ttf: "font/ttf",
1198
+ otf: "font/otf",
1199
+ woff: "font/woff",
1200
+ woff2: "font/woff2"
1201
+ };
1202
+ var FILE_TOOL = {
1203
+ name: "add_file_from_computer",
1204
+ 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>.",
1205
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "Path of the file, relative to the project folder (or absolute inside it)." } }, required: ["path"] }
1206
+ };
1207
+ var bytes = (v) => Buffer.byteLength(JSON.stringify(v) ?? "");
1208
+ var cut = (s, n) => typeof s === "string" ? s.length > n ? `${s.slice(0, n)}…` : s : undefined;
1209
+ var isChunk = (x) => !!x && (x.sessionUpdate === "agent_message_chunk" || x.sessionUpdate === "agent_thought_chunk" || x.sessionUpdate === "user_message_chunk") && x.content?.type === "text";
1210
+ function slimTool(u) {
1211
+ 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(" ");
1212
+ const out = { sessionUpdate: u.sessionUpdate, toolCallId: u.toolCallId };
1213
+ for (const k of ["title", "status", "kind"])
1214
+ if (typeof u[k] === "string")
1215
+ out[k] = cut(u[k], 300);
1216
+ if (texts)
1217
+ out.content = [{ type: "content", content: { type: "text", text: cut(texts, 400) } }];
1218
+ return out;
1219
+ }
1220
+ function slim(raw) {
1221
+ if (!raw || typeof raw !== "object")
1222
+ return [];
1223
+ const u = raw;
1224
+ if (isChunk(u)) {
1225
+ const t = String(u.content.text ?? "");
1226
+ const out = [];
1227
+ for (let i = 0;i < t.length || i === 0; i += MAX_TEXT)
1228
+ out.push({ sessionUpdate: u.sessionUpdate, content: { type: "text", text: t.slice(i, i + MAX_TEXT) } });
1229
+ return out;
1230
+ }
1231
+ if (u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update")
1232
+ return [slimTool(u)];
1233
+ if (u.sessionUpdate === "agent_message_chunk" || u.sessionUpdate === "agent_thought_chunk")
1234
+ return [];
1235
+ return bytes(u) > 64 * 1024 ? [] : [u];
1236
+ }
1237
+ function packUpdates(list) {
1238
+ const merged = [];
1239
+ for (const u of list.flatMap(slim)) {
1240
+ const last = merged[merged.length - 1];
1241
+ if (isChunk(u) && isChunk(last) && last.sessionUpdate === u.sessionUpdate && String(last.content.text).length + String(u.content.text).length <= MAX_TEXT)
1242
+ last.content = { type: "text", text: `${last.content.text}${u.content.text}` };
1243
+ else
1244
+ merged.push(isChunk(u) ? { ...u, content: { ...u.content } } : u);
1245
+ }
1246
+ const parts = [];
1247
+ let part = [];
1248
+ let size = 0;
1249
+ for (const u of merged) {
1250
+ const n = bytes(u) + 1;
1251
+ if (n > MAX_NEWS - 1024)
1252
+ continue;
1253
+ if (part.length && size + n > MAX_NEWS - 1024)
1254
+ parts.push(part), part = [], size = 0;
1255
+ part.push(u);
1256
+ size += n;
1257
+ }
1258
+ if (part.length)
1259
+ parts.push(part);
1260
+ return parts;
1261
+ }
1262
+ function commandText(req) {
1263
+ if (req.toolCall.kind !== "execute")
1264
+ return;
1265
+ const c = req.toolCall.rawInput?.command;
1266
+ if (Array.isArray(c))
1267
+ return c.map((a) => typeof a === "string" && /^[\w@%+=:,./-]+$/.test(a) ? a : JSON.stringify(String(a))).join(" ");
1268
+ return typeof c === "string" ? c : String(req.toolCall.title ?? "");
1269
+ }
1270
+ function historyFile(projectId, sessionId) {
1271
+ return path5.join(projectDir(projectId), "riwayat", `${crypto2.createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}.jsonl`);
1272
+ }
1273
+ function record(file, updates) {
1274
+ if (!updates.length)
1275
+ return;
1276
+ try {
1277
+ fs8.mkdirSync(path5.dirname(file), { recursive: true });
1278
+ fs8.appendFileSync(file, `${updates.map((u) => JSON.stringify(u)).join(`
1279
+ `)}
1280
+ `);
1281
+ if (fs8.statSync(file).size > MAX_HISTORY) {
1282
+ const text = fs8.readFileSync(file, "utf8");
1283
+ const from = text.indexOf(`
1284
+ `, text.length - MAX_HISTORY / 2);
1285
+ fs8.writeFileSync(file, from >= 0 ? text.slice(from + 1) : "");
1286
+ }
1287
+ } catch {}
1288
+ }
1289
+ function readHistory(file) {
1290
+ let text = "";
1291
+ try {
1292
+ text = fs8.readFileSync(file, "utf8");
1293
+ } catch {
1294
+ return { update: [], potong: false };
1295
+ }
1296
+ const out = [];
1297
+ let size = 0;
1298
+ const lines = text.split(`
1299
+ `).filter(Boolean);
1300
+ for (let i = lines.length - 1;i >= 0; i--) {
1301
+ size += Buffer.byteLength(lines[i]) + 1;
1302
+ if (size > HISTORY_ANSWER)
1303
+ return { update: out.reverse(), potong: true };
1304
+ try {
1305
+ out.push(JSON.parse(lines[i]));
1306
+ } catch {}
1307
+ }
1308
+ return { update: out.reverse(), potong: false };
1309
+ }
1310
+ function createAgentService(o) {
1311
+ const key = crypto2.randomBytes(24).toString("base64url");
1312
+ const routes = new Map;
1313
+ const sessionRoute = new Map;
1314
+ const permissions = new Map;
1315
+ const histories = new Map;
1316
+ const pending = new Map;
1317
+ let turn = 0;
1318
+ const sendUpdates = (sessionId) => {
1319
+ const list = pending.get(sessionId);
1320
+ pending.delete(sessionId);
1321
+ if (!list?.length)
1322
+ return;
1323
+ const parts = packUpdates(list);
1324
+ o.conn.news("agen", { sessionId, update: parts.shift() ?? [] });
1325
+ if (parts.length)
1326
+ pending.set(sessionId, parts.flat());
1327
+ };
1328
+ const ticker = setInterval(() => {
1329
+ const ids = [...pending.keys()];
1330
+ if (ids.length)
1331
+ sendUpdates(ids[turn++ % ids.length]);
1332
+ }, o.newsMs ?? 400);
1333
+ ticker.unref?.();
1334
+ const control = (sessionId, body) => {
1335
+ while (pending.has(sessionId))
1336
+ sendUpdates(sessionId);
1337
+ o.conn.news("agen", { sessionId, ...body });
1338
+ };
1339
+ const sessions = new AgentSessions({
1340
+ agent: (id) => readInstalled().find((a) => a.id === id),
1341
+ env: (id) => agentEnv(id),
1342
+ mcpServers: (_cwd, projectId, routeId) => [
1343
+ {
1344
+ name: "hypeframe",
1345
+ command: o.bridge.command,
1346
+ args: o.bridge.args,
1347
+ env: [
1348
+ ...o.bridge.env,
1349
+ { name: "HF_MCP_URL", value: `http://127.0.0.1:${o.port()}/agen/mcp/${projectId}/${routeId}` },
1350
+ { name: "HF_MCP_KUNCI", value: key }
1351
+ ]
1352
+ }
1353
+ ],
1354
+ onUpdate: (sessionId, list, info) => {
1355
+ const p = pending.get(sessionId);
1356
+ if (p)
1357
+ p.push(...list);
1358
+ else
1359
+ pending.set(sessionId, [...list]);
1360
+ const file = histories.get(sessionId);
1361
+ if (file && !info?.replay)
1362
+ record(file, packUpdates(list).flat());
1363
+ },
1364
+ onPermission: (sessionId, req, info) => new Promise((ok) => {
1365
+ const id = `i${crypto2.randomBytes(6).toString("hex")}`;
1366
+ const done = (v) => (permissions.delete(id), ok(v));
1367
+ permissions.set(id, done);
1368
+ setTimeout(() => permissions.has(id) && done(null), 5 * 60000).unref();
1369
+ control(sessionId, { izin: { id, judul: String(req.toolCall.title ?? ""), jenis: String(req.toolCall.kind ?? ""), perintah: commandText(req), wajibTanya: info.mustAsk, opsi: req.options } });
1370
+ }),
1371
+ onExit: (agentId, code) => o.conn.news("agen", { agentId, berhenti: code }),
1372
+ flushMs: o.flushMs ?? 100
1373
+ });
1374
+ const text = (c, k) => typeof c[k] === "string" ? c[k] : "";
1375
+ const work = {
1376
+ "agen.mulai": async (c) => {
1377
+ const agentId = text(c, "agentId");
1378
+ const projectId = text(c, "projectId");
1379
+ const tab = text(c, "tab");
1380
+ const a = readInstalled().find((x) => x.id === agentId);
1381
+ if (!a)
1382
+ throw new Error("Agen belum dipasang di mesin ini.");
1383
+ if (!a.ready)
1384
+ throw new Error("Agen belum masuk akun di mesin ini.");
1385
+ const { sessionId, dimuat, routeId, opsi } = await sessions.open({ agentId, projectId, resumeId: text(c, "resume") || undefined });
1386
+ const alat = Array.isArray(c.alat) ? c.alat : undefined;
1387
+ const r = routes.get(routeId);
1388
+ if (!r)
1389
+ routes.set(routeId, { dari: c.dari, tab, alat: alat ?? [], projectId });
1390
+ else {
1391
+ if (tab && r.tab === tab)
1392
+ r.dari = c.dari;
1393
+ if (alat)
1394
+ r.alat = alat;
1395
+ }
1396
+ sessionRoute.set(sessionId, routeId);
1397
+ histories.set(sessionId, historyFile(projectId, sessionId));
1398
+ return { sessionId, nama: a.name, sibuk: sessions.busy(sessionId), dimuat, opsi };
1399
+ },
1400
+ "agen.kirim": async (c) => {
1401
+ const sessionId = text(c, "sessionId");
1402
+ const routeId = sessionRoute.get(sessionId);
1403
+ if (!routeId || !sessions.agentOf(sessionId))
1404
+ throw new Error("Obrolan ini sudah berakhir. Mulai lagi.");
1405
+ if (sessions.busy(sessionId))
1406
+ throw new Error("Agen masih mengerjakan pesan sebelumnya.");
1407
+ const r = routes.get(routeId);
1408
+ if (r)
1409
+ r.dari = c.dari, r.tab = text(c, "tab") || r.tab;
1410
+ const file = histories.get(sessionId);
1411
+ if (file)
1412
+ record(file, packUpdates([{ sessionUpdate: "user_message_chunk", content: { type: "text", text: text(c, "teks") } }]).flat());
1413
+ sessions.prompt(sessionId, text(c, "teks")).then((res) => control(sessionId, { selesai: res.stopReason }), (e) => control(sessionId, { galat: e.message.slice(0, 300) }));
1414
+ return {};
1415
+ },
1416
+ "agen.izin": async (c) => {
1417
+ permissions.get(text(c, "izinId"))?.(typeof c.optionId === "string" ? c.optionId : null);
1418
+ return {};
1419
+ },
1420
+ "agen.batal": async (c) => {
1421
+ sessions.cancel(text(c, "sessionId"));
1422
+ return {};
1423
+ },
1424
+ "agen.opsi": async (c) => {
1425
+ const macam = text(c, "macam");
1426
+ if (!["model", "mode", "opsi"].includes(macam))
1427
+ throw new Error("Pilihan tidak dikenal.");
1428
+ return sessions.setOption(text(c, "sessionId"), { jenis: macam, id: text(c, "id"), nilai: text(c, "nilai") });
1429
+ },
1430
+ "agen.riwayat": async (c) => {
1431
+ try {
1432
+ return readHistory(historyFile(text(c, "projectId"), text(c, "sessionId")));
1433
+ } catch {
1434
+ return { update: [], potong: false };
1435
+ }
1436
+ }
1437
+ };
1438
+ async function sendFile(target, projectId, args) {
1439
+ const fail = (t) => ({ isError: true, content: [{ type: "text", text: t }] });
1440
+ const p = typeof args?.path === "string" ? String(args.path) : "";
1441
+ const folder = projectDir(projectId);
1442
+ if (!p || !insideFolder(folder, p))
1443
+ return fail(`Only files inside the HypeFrame project folder (${folder}) can be added.`);
1444
+ const file = path5.resolve(folder, p);
1445
+ const st = fs8.statSync(file, { throwIfNoEntry: false });
1446
+ if (!st?.isFile())
1447
+ return fail(`${p} is not a file in the project folder.`);
1448
+ const nama = path5.basename(file).slice(0, 120);
1449
+ const mime = MEDIA[path5.extname(file).slice(1).toLowerCase()];
1450
+ if (!mime)
1451
+ return fail(`${nama}: only images, audio, video, fonts and Lottie/JSON files can be added to a HypeFrame project.`);
1452
+ if (st.size > MAX_FILE2)
1453
+ 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.`);
1454
+ const data = fs8.readFileSync(file).toString("base64");
1455
+ const n = Math.max(1, Math.ceil(data.length / PIECE));
1456
+ const id = crypto2.randomBytes(8).toString("hex");
1457
+ let last = {};
1458
+ for (let i = 0;i < n; i++) {
1459
+ 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) } });
1460
+ if (last.ok === false) {
1461
+ const error = String(last.error) in ERRORS ? String(last.error) : "tab";
1462
+ o.onToolError?.(error);
1463
+ return fail(ERRORS[error]);
1464
+ }
1465
+ if (last.isError)
1466
+ return { isError: true, content: Array.isArray(last.content) ? last.content : [] };
1467
+ }
1468
+ return { isError: false, content: Array.isArray(last.content) ? last.content : [] };
1469
+ }
1470
+ const reply = (res, status, body) => {
1471
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
1472
+ res.end(body === undefined ? "" : JSON.stringify(body));
1473
+ };
1474
+ async function route(req, res, url) {
1475
+ const m = url.pathname.match(/^\/agen\/mcp\/([A-Za-z0-9_-]{1,80})\/([A-Za-z0-9_-]{1,40})$/);
1476
+ if (!m)
1477
+ return false;
1478
+ const auth = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
1479
+ if (req.method !== "POST" || auth.length !== key.length || !crypto2.timingSafeEqual(Buffer.from(auth), Buffer.from(key)))
1480
+ return reply(res, 401, { error: "unauthorized" }), true;
1481
+ let s = "";
1482
+ for await (const d of req)
1483
+ if ((s += d).length > 8 * 1024 * 1024)
1484
+ return reply(res, 413), true;
1485
+ let msg;
1486
+ try {
1487
+ msg = JSON.parse(s);
1488
+ } catch {
1489
+ return reply(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }), true;
1490
+ }
1491
+ if (msg.id === undefined || msg.id === null)
1492
+ return reply(res, 202), true;
1493
+ const ok = (result) => reply(res, 200, { jsonrpc: "2.0", id: msg.id, result });
1494
+ const found = routes.get(m[2]);
1495
+ const target = found && found.projectId === m[1] ? found : undefined;
1496
+ switch (msg.method) {
1497
+ case "initialize":
1498
+ 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;
1499
+ case "ping":
1500
+ return ok({}), true;
1501
+ case "tools/list":
1502
+ return ok({ tools: target ? [...target.alat, FILE_TOOL] : [] }), true;
1503
+ case "tools/call": {
1504
+ if (!target)
1505
+ return o.onToolError?.("tab"), ok({ isError: true, content: [{ type: "text", text: NOT_OPEN }] }), true;
1506
+ if (msg.params?.name === FILE_TOOL.name)
1507
+ return ok(await sendFile(target, target.projectId, msg.params?.arguments)), true;
1508
+ const body = { nama: String(msg.params?.name ?? ""), arg: msg.params?.arguments ?? {} };
1509
+ if (bytes(body) > MAX_TOOL_ARGS)
1510
+ 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;
1511
+ const a = await o.conn.request(target.dari, "alat", body);
1512
+ if (a.ok === false) {
1513
+ const error = String(a.error) in ERRORS ? String(a.error) : "tab";
1514
+ o.onToolError?.(error);
1515
+ return ok({ isError: true, content: [{ type: "text", text: ERRORS[error] }] }), true;
1516
+ }
1517
+ return ok({ isError: !!a.isError, content: Array.isArray(a.content) ? a.content : [] }), true;
1518
+ }
1519
+ default:
1520
+ return reply(res, 200, { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `Method not found: ${msg.method}` } }), true;
1521
+ }
1522
+ }
1523
+ function capabilities() {
1524
+ 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 }));
1525
+ }
1526
+ return { work, route, capabilities, key, stop: () => (clearInterval(ticker), sessions.stopAll()) };
1527
+ }
1528
+
1529
+ // src/agent/mcp-bridge.ts
1530
+ import fs10 from "node:fs";
1531
+ import path7 from "node:path";
1532
+ import readline2 from "node:readline";
1533
+
1534
+ // src/util/runtime.ts
1535
+ import fs9 from "node:fs";
1536
+ import path6 from "node:path";
1537
+ function isStandalone() {
1538
+ return path6.basename(process.execPath).toLowerCase().startsWith("hypeframe");
1539
+ }
1540
+ function runtimeLabel() {
1541
+ const bun = process.versions.bun;
1542
+ return bun && !isStandalone() ? `Bun ${bun}` : isStandalone() ? `Bun ${bun ?? "?"} (standalone)` : `Node ${process.versions.node}`;
1543
+ }
1544
+ function launchCommand() {
1545
+ if (isStandalone())
1546
+ return [process.execPath];
1547
+ try {
1548
+ const script = fs9.realpathSync(process.argv[1] || "");
1549
+ return /[\\/]_npx[\\/]/.test(script) ? null : [process.execPath, script];
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ }
1554
+ var INSTALL_URL = "https://hype-frame.com/install";
1555
+
1556
+ // src/agent/mcp-bridge.ts
1557
+ var BRIDGE_SOURCE = `// HypeFrame MCP bridge (written by hypeframe; do not edit). stdin JSON-RPC lines -> engine -> stdout.
1558
+ import readline from 'node:readline';
1559
+ const url = process.env.HF_MCP_URL, key = process.env.HF_MCP_KUNCI;
1560
+ if (!url || !key) { process.stderr.write('HF_MCP_URL and HF_MCP_KUNCI are required\\n'); process.exit(2); }
1561
+ const out = (m) => process.stdout.write(JSON.stringify(m) + '\\n');
1562
+ const busy = new Set();
1563
+ const rl = readline.createInterface({ input: process.stdin });
1564
+ rl.on('line', (line) => {
1565
+ if (!line.trim()) return;
1566
+ let m = null;
1567
+ try { m = JSON.parse(line); } catch { return out({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
1568
+ const p = (async () => {
1569
+ try {
1570
+ const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + key }, body: line });
1571
+ if (r.status === 202) return;
1572
+ const t = (await r.text()).trim();
1573
+ if (t) process.stdout.write(t + '\\n');
1574
+ } catch (e) {
1575
+ if (m && m.id !== undefined) out({ jsonrpc: '2.0', id: m.id, error: { code: -32603, message: 'HypeFrame engine is not reachable: ' + e.message } });
1576
+ }
1577
+ })();
1578
+ busy.add(p);
1579
+ p.finally(() => busy.delete(p));
1580
+ });
1581
+ rl.on('close', () => Promise.all(busy).then(() => process.exit(0)));
1582
+ `;
1583
+ function bridgeLaunch() {
1584
+ const file = path7.join(agentDir(), "mcp-bridge.mjs");
1585
+ let now = "";
1586
+ try {
1587
+ now = fs10.readFileSync(file, "utf8");
1588
+ } catch {}
1589
+ if (now !== BRIDGE_SOURCE)
1590
+ fs10.writeFileSync(file, BRIDGE_SOURCE);
1591
+ return { command: process.execPath, args: [file], env: isStandalone() ? [{ name: "BUN_BE_BUN", value: "1" }] : [] };
1592
+ }
1593
+ async function runMcpBridge() {
1594
+ const url = process.env.HF_MCP_URL;
1595
+ const key = process.env.HF_MCP_KUNCI;
1596
+ if (!url || !key) {
1597
+ process.stderr.write(`hypeframe mcp-bridge: HF_MCP_URL and HF_MCP_KUNCI are required
1598
+ `);
1599
+ process.exit(2);
1600
+ }
1601
+ const out = (m) => process.stdout.write(`${JSON.stringify(m)}
1602
+ `);
1603
+ const rl = readline2.createInterface({ input: process.stdin });
1604
+ const busy = new Set;
1605
+ rl.on("line", (line) => {
1606
+ if (!line.trim())
1607
+ return;
1608
+ let m = null;
1609
+ try {
1610
+ m = JSON.parse(line);
1611
+ } catch {
1612
+ return out({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
1613
+ }
1614
+ const p = (async () => {
1615
+ try {
1616
+ const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key}` }, body: line });
1617
+ if (r.status === 202)
1618
+ return;
1619
+ const text = await r.text();
1620
+ if (text.trim())
1621
+ process.stdout.write(`${text.trim()}
1622
+ `);
1623
+ } catch (e) {
1624
+ if (m && m.id !== undefined)
1625
+ out({ jsonrpc: "2.0", id: m.id, error: { code: -32603, message: `HypeFrame engine is not reachable: ${e.message}` } });
1626
+ }
1627
+ })();
1628
+ busy.add(p);
1629
+ p.finally(() => busy.delete(p));
1630
+ });
1631
+ await new Promise((ok) => rl.on("close", ok));
1632
+ await Promise.all(busy);
1633
+ }
1634
+
1635
+ // src/config/lock.ts
1636
+ import fs11 from "node:fs";
527
1637
  class AlreadyRunning extends Error {
528
1638
  code = "SUDAH_JALAN";
529
1639
  }
@@ -537,7 +1647,7 @@ var alive = (pid) => {
537
1647
  };
538
1648
  function runningPid() {
539
1649
  try {
540
- const pid = Number(fs5.readFileSync(lockFile(), "utf8"));
1650
+ const pid = Number(fs11.readFileSync(lockFile(), "utf8"));
541
1651
  return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
542
1652
  } catch {
543
1653
  return null;
@@ -547,13 +1657,13 @@ function singleInstance() {
547
1657
  const f = lockFile();
548
1658
  for (let attempt = 0;attempt < 2; attempt++) {
549
1659
  try {
550
- const fd = fs5.openSync(f, "wx");
551
- fs5.writeSync(fd, String(process.pid));
552
- fs5.closeSync(fd);
1660
+ const fd = fs11.openSync(f, "wx");
1661
+ fs11.writeSync(fd, String(process.pid));
1662
+ fs11.closeSync(fd);
553
1663
  const release = () => {
554
1664
  try {
555
- if (fs5.readFileSync(f, "utf8") === String(process.pid))
556
- fs5.rmSync(f, { force: true });
1665
+ if (fs11.readFileSync(f, "utf8") === String(process.pid))
1666
+ fs11.rmSync(f, { force: true });
557
1667
  } catch {}
558
1668
  process.off("exit", release);
559
1669
  };
@@ -562,35 +1672,22 @@ function singleInstance() {
562
1672
  } catch (e) {
563
1673
  if (e.code !== "EEXIST")
564
1674
  throw e;
565
- const pid = Number(fs5.readFileSync(f, "utf8"));
1675
+ const pid = Number(fs11.readFileSync(f, "utf8"));
566
1676
  if (Number.isInteger(pid) && pid > 0 && alive(pid))
567
1677
  throw new AlreadyRunning("engine already running");
568
- fs5.rmSync(f, { force: true });
1678
+ fs11.rmSync(f, { force: true });
569
1679
  }
570
1680
  }
571
1681
  throw new AlreadyRunning("engine already running");
572
1682
  }
573
1683
 
574
- // packages/hypeframe/src/config/version.ts
575
- import fs6 from "node:fs";
576
- function readPkg() {
577
- for (const rel of ["../package.json", "../../package.json"]) {
578
- try {
579
- const p = JSON.parse(fs6.readFileSync(new URL(rel, import.meta.url), "utf8"));
580
- if (p.name === "hypeframe")
581
- return p;
582
- } catch {}
583
- }
584
- return { version: "0.0.0" };
585
- }
586
- var VERSION = process.env.HF_MESIN_VERSI || readPkg().version;
587
-
588
- // packages/hypeframe/src/engine/connection.ts
589
- import { EventEmitter } from "node:events";
1684
+ // src/engine/connection.ts
1685
+ import crypto3 from "node:crypto";
1686
+ import { EventEmitter as EventEmitter2 } from "node:events";
590
1687
  import WebSocket from "ws";
591
1688
  var SILENCE_MAX_MS = 70000;
592
1689
 
593
- class Connection extends EventEmitter {
1690
+ class Connection extends EventEmitter2 {
594
1691
  o;
595
1692
  url;
596
1693
  ws = null;
@@ -626,6 +1723,33 @@ class Connection extends EventEmitter {
626
1723
  news(kind, body = {}) {
627
1724
  this.send({ ...body, t: "kabar", jenis: kind });
628
1725
  }
1726
+ nextReq = 1;
1727
+ waiting = new Map;
1728
+ request(ke, kind, body, timeoutMs = 55000) {
1729
+ if (!this.connected)
1730
+ return Promise.resolve({ ok: false, error: "terputus" });
1731
+ const id = `q${this.nextReq++}${crypto3.randomBytes(6).toString("hex")}`;
1732
+ return new Promise((ok) => {
1733
+ const timer = setTimeout(() => (this.waiting.delete(id), ok({ ok: false, error: "waktu" })), timeoutMs);
1734
+ timer.unref?.();
1735
+ this.waiting.set(id, { ok, timer });
1736
+ this.send({ ...body, t: "minta", ke, id, jenis: kind });
1737
+ });
1738
+ }
1739
+ answer(m) {
1740
+ const w = this.waiting.get(String(m.id));
1741
+ if (!w)
1742
+ return;
1743
+ clearTimeout(w.timer);
1744
+ this.waiting.delete(String(m.id));
1745
+ const { t: _t, id: _id, dari: _dari, ...rest } = m;
1746
+ w.ok(rest);
1747
+ }
1748
+ dropWaiting() {
1749
+ for (const w of this.waiting.values())
1750
+ clearTimeout(w.timer), w.ok({ ok: false, error: "terputus" });
1751
+ this.waiting.clear();
1752
+ }
629
1753
  get connected() {
630
1754
  return this.ws?.readyState === WebSocket.OPEN && !!this.id;
631
1755
  }
@@ -664,6 +1788,8 @@ class Connection extends EventEmitter {
664
1788
  const result = await this.o.handler(m);
665
1789
  if (ws === this.ws)
666
1790
  this.send({ t: "balas", ke: m.dari, id: m.id, ...result });
1791
+ } else if (m.t === "jawab") {
1792
+ this.answer(m);
667
1793
  }
668
1794
  });
669
1795
  ws.on("error", () => {
@@ -674,6 +1800,7 @@ class Connection extends EventEmitter {
674
1800
  if (ws !== this.ws)
675
1801
  return;
676
1802
  this.id = null;
1803
+ this.dropWaiting();
677
1804
  if (code === CloseCode.TokenRevoked) {
678
1805
  deleteAccount();
679
1806
  this.running = false;
@@ -692,21 +1819,22 @@ class Connection extends EventEmitter {
692
1819
  }
693
1820
  }
694
1821
 
695
- // packages/hypeframe/src/engine/handler.ts
1822
+ // src/engine/handler.ts
696
1823
  function createHandler(work) {
697
1824
  return async function handle(c) {
698
1825
  const kind = String(c?.jenis || "");
699
- if (!ALLOWED_KINDS.includes(kind))
1826
+ const fn = ALLOWED_KINDS.includes(kind) ? work[kind] : undefined;
1827
+ if (!fn)
700
1828
  return { ok: false, error: "jenis" };
701
1829
  try {
702
- return { ok: true, ...await work[kind](c) };
1830
+ return { ok: true, ...await fn(c) };
703
1831
  } catch (e) {
704
1832
  return { ok: false, error: "galat", pesan: String(e?.message || e).slice(0, 200) };
705
1833
  }
706
1834
  };
707
1835
  }
708
1836
 
709
- // packages/hypeframe/src/engine/pairing.ts
1837
+ // src/engine/pairing.ts
710
1838
  var sleep = (ms, signal) => new Promise((ok, fail) => {
711
1839
  const timer = setTimeout(ok, ms);
712
1840
  signal?.addEventListener("abort", () => (clearTimeout(timer), fail(new Error("Dibatalkan."))), { once: true });
@@ -782,17 +1910,17 @@ async function pair(o) {
782
1910
  }
783
1911
  }
784
1912
 
785
- // packages/hypeframe/src/render/chrome.ts
1913
+ // src/render/chrome.ts
786
1914
  import { execFileSync } from "node:child_process";
787
- import fs7 from "node:fs";
1915
+ import fs12 from "node:fs";
788
1916
  import http from "node:http";
789
- import path3 from "node:path";
1917
+ import path8 from "node:path";
790
1918
  import { Browser, detectBrowserPlatform, getInstalledBrowsers, install, resolveBuildId } from "@puppeteer/browsers";
791
1919
  import puppeteer from "puppeteer-core";
792
1920
  function candidates() {
793
1921
  const e = process.env;
794
1922
  if (process.platform === "win32") {
795
- return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [path3.join(d, "Google", "Chrome", "Application", "chrome.exe"), path3.join(d, "Microsoft", "Edge", "Application", "msedge.exe")]);
1923
+ return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [path8.join(d, "Google", "Chrome", "Application", "chrome.exe"), path8.join(d, "Microsoft", "Edge", "Application", "msedge.exe")]);
796
1924
  }
797
1925
  if (process.platform === "darwin") {
798
1926
  return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
@@ -810,13 +1938,13 @@ function candidates() {
810
1938
  function findChrome() {
811
1939
  const forced = process.env.HYPEFRAME_CHROME;
812
1940
  if (forced)
813
- return fs7.existsSync(forced) ? forced : null;
814
- return candidates().find((p) => fs7.existsSync(p)) || null;
1941
+ return fs12.existsSync(forced) ? forced : null;
1942
+ return candidates().find((p) => fs12.existsSync(p)) || null;
815
1943
  }
816
1944
  async function cachedChrome(cacheDir) {
817
1945
  try {
818
- const all = await getInstalledBrowsers({ cacheDir: path3.join(cacheDir, "chrome") });
819
- return all.find((b) => b.browser === Browser.CHROME && fs7.existsSync(b.executablePath))?.executablePath ?? null;
1946
+ const all = await getInstalledBrowsers({ cacheDir: path8.join(cacheDir, "chrome") });
1947
+ return all.find((b) => b.browser === Browser.CHROME && fs12.existsSync(b.executablePath))?.executablePath ?? null;
820
1948
  } catch {
821
1949
  return null;
822
1950
  }
@@ -830,7 +1958,7 @@ async function prepareChrome(cacheDir, progress = () => {
830
1958
  const platform = detectBrowserPlatform();
831
1959
  if (!platform)
832
1960
  throw new Error("Sistem ini belum didukung untuk render (Chrome tidak tersedia).");
833
- const dir = path3.join(cacheDir, "chrome");
1961
+ const dir = path8.join(cacheDir, "chrome");
834
1962
  const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
835
1963
  progress(0, `Chrome ${buildId}`);
836
1964
  const r = await install({
@@ -879,17 +2007,97 @@ async function checkChrome(chrome, { gpu = false } = {}) {
879
2007
  }
880
2008
  }
881
2009
 
882
- // packages/hypeframe/src/render/job.ts
883
- import { spawn } from "node:child_process";
884
- import crypto from "node:crypto";
885
- import fs8 from "node:fs";
2010
+ // src/render/ffmpeg.ts
2011
+ import crypto4 from "node:crypto";
2012
+ import fs13 from "node:fs";
886
2013
  import fsp from "node:fs/promises";
887
- import path4 from "node:path";
2014
+ import path9 from "node:path";
2015
+ import { pipeline } from "node:stream/promises";
2016
+ import { Readable } from "node:stream";
2017
+ import zlib from "node:zlib";
2018
+ var FFMPEG_RELEASE = "b6.0";
2019
+ var BASE = `https://github.com/eugeneware/ffmpeg-static/releases/download/${FFMPEG_RELEASE}/`;
2020
+ var FFMPEG_PINNED = {
2021
+ "win32-x64": { sha256: "450d66226c79405c724e821f291cab0911e934bfa9fa2231adcab587f3e07b50", size: 28894894 },
2022
+ "linux-x64": { sha256: "17c1ae10b52ac499180679fe6ba77e17642390c4eedb0f1e3b0ac045da55128f", size: 28928723 },
2023
+ "linux-arm64": { sha256: "2b708b2d15041d2a192c1db24c7a8a1d24f645a8242dce1c744ff2392b86ada1", size: 25131803 },
2024
+ "darwin-x64": { sha256: "a12354fce7eb62361473bbe10d53a1893695babd35869ec8e92e5dfea8d0440b", size: 25067704 },
2025
+ "darwin-arm64": { sha256: "6be74d6f449889c2e87a75873894f8520cad56c08ac76f2a628d85b0519daaca", size: 19253088 }
2026
+ };
2027
+ var exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
2028
+ var cached2 = (cacheDir) => path9.join(cacheDir, "ffmpeg", FFMPEG_RELEASE, exe);
2029
+ async function findFfmpeg(cacheDir) {
2030
+ const forced = process.env.HYPEFRAME_FFMPEG;
2031
+ if (forced)
2032
+ return fs13.existsSync(forced) ? forced : null;
2033
+ try {
2034
+ const mod = await import("ffmpeg-static");
2035
+ const p = typeof mod.default === "string" ? mod.default : null;
2036
+ if (p && fs13.existsSync(p))
2037
+ return p;
2038
+ } catch {}
2039
+ const c = cached2(cacheDir);
2040
+ return fs13.existsSync(c) ? c : null;
2041
+ }
2042
+ async function downloadVerified(url, sha256, dest, progress = () => {
2043
+ return;
2044
+ }, gunzip = false) {
2045
+ const r = await fetch(url, { signal: AbortSignal.timeout(900000) });
2046
+ if (!r.ok || !r.body)
2047
+ throw new Error(`download ${r.status}`);
2048
+ const total = Number(r.headers.get("content-length")) || 0;
2049
+ await fsp.mkdir(path9.dirname(dest), { recursive: true });
2050
+ const tmp = `${dest}.download`;
2051
+ const hash = crypto4.createHash("sha256");
2052
+ let got = 0;
2053
+ let last = -10;
2054
+ const body = Readable.fromWeb(r.body).on("data", (c) => {
2055
+ hash.update(c);
2056
+ got += c.length;
2057
+ const pct = total ? Math.floor(got / total * 100) : 0;
2058
+ if (pct - last >= 10)
2059
+ last = pct, progress(pct);
2060
+ });
2061
+ await pipeline(body, fs13.createWriteStream(tmp));
2062
+ if (hash.digest("hex") !== sha256) {
2063
+ await fsp.rm(tmp, { force: true });
2064
+ throw new Error("ffmpeg: sidik unduhan tidak cocok, berkas ditolak.");
2065
+ }
2066
+ if (gunzip) {
2067
+ await pipeline(fs13.createReadStream(tmp), zlib.createGunzip(), fs13.createWriteStream(`${tmp}.raw`));
2068
+ await fsp.rm(tmp, { force: true });
2069
+ await fsp.rename(`${tmp}.raw`, dest);
2070
+ } else
2071
+ await fsp.rename(tmp, dest);
2072
+ if (process.platform !== "win32")
2073
+ await fsp.chmod(dest, 493);
2074
+ }
2075
+ async function prepareFfmpeg(cacheDir, progress = () => {
2076
+ return;
2077
+ }) {
2078
+ const found = await findFfmpeg(cacheDir);
2079
+ if (found)
2080
+ return found;
2081
+ const key = `${process.platform}-${process.arch}`;
2082
+ const pin = FFMPEG_PINNED[key];
2083
+ if (!pin)
2084
+ throw new Error(`ffmpeg tidak tersedia untuk ${key}`);
2085
+ progress(0);
2086
+ await downloadVerified(`${BASE}ffmpeg-${key}.gz`, pin.sha256, cached2(cacheDir), progress, true);
2087
+ return cached2(cacheDir);
2088
+ }
2089
+
2090
+ // src/render/job.ts
2091
+ import { spawn as spawn2 } from "node:child_process";
2092
+ import crypto5 from "node:crypto";
2093
+ import fs14 from "node:fs";
2094
+ import fsp2 from "node:fs/promises";
2095
+ import path10 from "node:path";
888
2096
  import puppeteer2 from "puppeteer-core";
889
2097
  var LIMIT_SECONDS = 1800;
890
2098
  function run(cmd, args, limitSeconds = 600) {
891
2099
  return new Promise((ok, fail) => {
892
- const p = spawn(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
2100
+ const p = spawn2(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
893
2101
  let err = "";
894
2102
  p.stderr.on("data", (d) => err = (err + d).slice(-2000));
895
2103
  const timer = setTimeout(() => p.kill("SIGKILL"), limitSeconds * 1000);
@@ -901,7 +2109,7 @@ function run(cmd, args, limitSeconds = 600) {
901
2109
  function saveBody(req, to, max) {
902
2110
  return new Promise((ok, fail) => {
903
2111
  let n = 0;
904
- const out = fs8.createWriteStream(to);
2112
+ const out = fs14.createWriteStream(to);
905
2113
  req.on("data", (d) => {
906
2114
  n += d.length;
907
2115
  if (n > max)
@@ -932,7 +2140,7 @@ function createJobRunner(o) {
932
2140
  const renderer = async (task, { progress, signal }) => {
933
2141
  if (task.kind === "klip" && task.transparent && !transparent)
934
2142
  throw new Error(EngineError.NoTransparent);
935
- const key = crypto.randomBytes(16).toString("hex");
2143
+ const key = crypto5.randomBytes(16).toString("hex");
936
2144
  let finish;
937
2145
  const finished = new Promise((ok) => finish = ok);
938
2146
  running.set(task.job, { key, task, progress, finish });
@@ -943,9 +2151,9 @@ function createJobRunner(o) {
943
2151
  let browser;
944
2152
  try {
945
2153
  progress(0, "Menyiapkan");
946
- const profile = path4.join(task.dir, "profil");
947
- await fsp.mkdir(path4.join(profile, "Default"), { recursive: true });
948
- await fsp.writeFile(path4.join(profile, "Default", "Preferences"), JSON.stringify({ webkit: { webprefs: { fonts: { standard: { Zyyy: "Roboto" }, sansserif: { Zyyy: "Roboto" }, serif: { Zyyy: "Noto Serif" } } } } }));
2154
+ const profile = path10.join(task.dir, "profil");
2155
+ await fsp2.mkdir(path10.join(profile, "Default"), { recursive: true });
2156
+ await fsp2.writeFile(path10.join(profile, "Default", "Preferences"), JSON.stringify({ webkit: { webprefs: { fonts: { standard: { Zyyy: "Roboto" }, sansserif: { Zyyy: "Roboto" }, serif: { Zyyy: "Noto Serif" } } } } }));
949
2157
  browser = await puppeteer2.launch({
950
2158
  executablePath: chrome,
951
2159
  headless: true,
@@ -975,11 +2183,11 @@ function createJobRunner(o) {
975
2183
  if (result.error)
976
2184
  throw new Error(result.error);
977
2185
  progress(99, clip ? "Menyelesaikan klip" : "Menyelesaikan video");
978
- const raw = path4.join(task.dir, "mentah.mp4");
2186
+ const raw = path10.join(task.dir, "mentah.mp4");
979
2187
  const webm = clip && task.transparent;
980
- const file = path4.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
2188
+ const file = path10.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
981
2189
  if (clip)
982
- await fsp.rename(raw, file);
2190
+ await fsp2.rename(raw, file);
983
2191
  else
984
2192
  await run(ffmpeg, ["-y", "-v", "error", "-i", raw, "-map", "0", "-c:v", "copy", ...result.audio === "opus" ? ["-c:a", "aac", "-b:a", "192k"] : ["-c:a", "copy"], "-movflags", "+faststart", file]);
985
2193
  return { file, type: webm ? "video/webm" : "video/mp4" };
@@ -1004,11 +2212,11 @@ function createJobRunner(o) {
1004
2212
  return res.writeHead(403), res.end(), true;
1005
2213
  const pkg = r.task.packageDir;
1006
2214
  if (m[2] === "proyek.json" || m[2] === "klip.json" || m[3]) {
1007
- const f = m[3] ? path4.join(pkg, "aset", m[3]) : path4.join(pkg, m[2]);
1008
- if (!fs8.existsSync(f))
2215
+ const f = m[3] ? path10.join(pkg, "aset", m[3]) : path10.join(pkg, m[2]);
2216
+ if (!fs14.existsSync(f))
1009
2217
  return res.writeHead(404), res.end(), true;
1010
- res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp.stat(f)).size });
1011
- fs8.createReadStream(f).pipe(res);
2218
+ res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp2.stat(f)).size });
2219
+ fs14.createReadStream(f).pipe(res);
1012
2220
  return true;
1013
2221
  }
1014
2222
  if (m[2] === "kemajuan") {
@@ -1025,7 +2233,7 @@ function createJobRunner(o) {
1025
2233
  r.finish({ error: String(b.pesan || "Render gagal.").slice(0, 300) });
1026
2234
  return res.writeHead(204), res.end(), true;
1027
2235
  }
1028
- await saveBody(req, path4.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
2236
+ await saveBody(req, path10.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
1029
2237
  r.finish({ audio: String(req.headers["x-kodek-audio"] || "") });
1030
2238
  res.writeHead(204);
1031
2239
  res.end();
@@ -1034,10 +2242,10 @@ function createJobRunner(o) {
1034
2242
  return { renderer, route, setPort: (p) => void (port = p) };
1035
2243
  }
1036
2244
 
1037
- // packages/hypeframe/src/render/page.ts
1038
- import fs9 from "node:fs";
1039
- import fsp2 from "node:fs/promises";
1040
- import path5 from "node:path";
2245
+ // src/render/page.ts
2246
+ import fs15 from "node:fs";
2247
+ import fsp3 from "node:fs/promises";
2248
+ import path11 from "node:path";
1041
2249
  var TYPES = {
1042
2250
  ".html": "text/html; charset=utf-8",
1043
2251
  ".js": "text/javascript",
@@ -1058,13 +2266,13 @@ var SAFE_PATH = /^[\w@.+-]+(?:\/[\w@.+-]+)*$/;
1058
2266
  var VERSION_ID = /^[0-9a-f]{12}$/;
1059
2267
  function createPage({ web, cacheDir }) {
1060
2268
  const base = `${String(web || "").replace(/\/+$/, "")}/render/`;
1061
- const root = path5.join(cacheDir, "halaman");
2269
+ const root = path11.join(cacheDir, "halaman");
1062
2270
  let version = null;
1063
- const versionDir = () => path5.join(root, version);
2271
+ const versionDir = () => path11.join(root, version);
1064
2272
  const pending = new Map;
1065
2273
  async function download(rel) {
1066
- const target = path5.join(versionDir(), rel);
1067
- if (fs9.existsSync(target))
2274
+ const target = path11.join(versionDir(), rel);
2275
+ if (fs15.existsSync(target))
1068
2276
  return target;
1069
2277
  if (!pending.has(rel)) {
1070
2278
  pending.set(rel, (async () => {
@@ -1072,9 +2280,9 @@ function createPage({ web, cacheDir }) {
1072
2280
  if (!r.ok)
1073
2281
  throw Object.assign(new Error(`halaman ${rel}: ${r.status}`), { status: r.status });
1074
2282
  const body = Buffer.from(await r.arrayBuffer());
1075
- await fsp2.mkdir(path5.dirname(target), { recursive: true });
1076
- await fsp2.writeFile(`${target}.tmp`, body);
1077
- await fsp2.rename(`${target}.tmp`, target);
2283
+ await fsp3.mkdir(path11.dirname(target), { recursive: true });
2284
+ await fsp3.writeFile(`${target}.tmp`, body);
2285
+ await fsp3.rename(`${target}.tmp`, target);
1078
2286
  return target;
1079
2287
  })().finally(() => pending.delete(rel)));
1080
2288
  }
@@ -1095,11 +2303,11 @@ function createPage({ web, cacheDir }) {
1095
2303
  if (typeof f === "string" && SAFE_PATH.test(f))
1096
2304
  await download(f);
1097
2305
  if (old !== version) {
1098
- const all = (await fsp2.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
1099
- const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp2.stat(path5.join(root, d))).mtimeMs })));
2306
+ const all = (await fsp3.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
2307
+ const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(path11.join(root, d))).mtimeMs })));
1100
2308
  for (const { d } of dated.sort((a, b) => b.t - a.t).slice(2))
1101
2309
  if (d !== version)
1102
- await fsp2.rm(path5.join(root, d), { recursive: true, force: true });
2310
+ await fsp3.rm(path11.join(root, d), { recursive: true, force: true });
1103
2311
  }
1104
2312
  return { version };
1105
2313
  }
@@ -1116,8 +2324,8 @@ function createPage({ web, cacheDir }) {
1116
2324
  return res.writeHead(404), res.end(), true;
1117
2325
  try {
1118
2326
  const f = await download(rel);
1119
- res.writeHead(200, { "content-type": TYPES[path5.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
1120
- fs9.createReadStream(f).pipe(res);
2327
+ res.writeHead(200, { "content-type": TYPES[path11.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
2328
+ fs15.createReadStream(f).pipe(res);
1121
2329
  } catch (e) {
1122
2330
  res.writeHead(e.status === 404 ? 404 : 502);
1123
2331
  res.end();
@@ -1133,15 +2341,15 @@ function createPage({ web, cacheDir }) {
1133
2341
  };
1134
2342
  }
1135
2343
 
1136
- // packages/hypeframe/src/render/service.ts
1137
- import crypto2 from "node:crypto";
1138
- import fs10 from "node:fs";
1139
- import fsp3 from "node:fs/promises";
2344
+ // src/render/service.ts
2345
+ import crypto6 from "node:crypto";
2346
+ import fs16 from "node:fs";
2347
+ import fsp4 from "node:fs/promises";
1140
2348
  import http2 from "node:http";
1141
- import path6 from "node:path";
2349
+ import path12 from "node:path";
1142
2350
  import yauzl from "yauzl";
1143
2351
  var ACTIVE = new Set(["unggah", "antre", "jalan"]);
1144
- var safeEqual = (a, b) => a.length === b.length && crypto2.timingSafeEqual(Buffer.from(a), Buffer.from(b));
2352
+ var safeEqual = (a, b) => a.length === b.length && crypto6.timingSafeEqual(Buffer.from(a), Buffer.from(b));
1145
2353
  var BAD_ENTRY = /relative path|absolute path|invalid characters/i;
1146
2354
  function listZip(f) {
1147
2355
  return new Promise((ok, fail) => {
@@ -1165,14 +2373,14 @@ function extractZip(f, to) {
1165
2373
  zip.on("entry", (en) => {
1166
2374
  if (en.fileName.endsWith("/"))
1167
2375
  return zip.readEntry();
1168
- const target = path6.join(to, en.fileName);
1169
- if (!target.startsWith(to + path6.sep))
2376
+ const target = path12.join(to, en.fileName);
2377
+ if (!target.startsWith(to + path12.sep))
1170
2378
  return fail(new Error(EngineError.BadPackage));
1171
- fs10.mkdirSync(path6.dirname(target), { recursive: true });
2379
+ fs16.mkdirSync(path12.dirname(target), { recursive: true });
1172
2380
  zip.openReadStream(en, (e2, s) => {
1173
2381
  if (e2 || !s)
1174
2382
  return fail(e2 ?? new Error("zip"));
1175
- const out = fs10.createWriteStream(target);
2383
+ const out = fs16.createWriteStream(target);
1176
2384
  s.pipe(out);
1177
2385
  out.on("finish", () => zip.readEntry());
1178
2386
  out.on("error", fail);
@@ -1187,13 +2395,13 @@ function extractZip(f, to) {
1187
2395
  function saveBody2(req, to, max) {
1188
2396
  return new Promise((ok, fail) => {
1189
2397
  let n = 0;
1190
- const out = fs10.createWriteStream(to);
2398
+ const out = fs16.createWriteStream(to);
1191
2399
  req.on("data", (d) => {
1192
2400
  n += d.length;
1193
2401
  if (n > max) {
1194
2402
  req.destroy();
1195
2403
  out.destroy();
1196
- fs10.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
2404
+ fs16.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
1197
2405
  }
1198
2406
  });
1199
2407
  req.pipe(out);
@@ -1221,9 +2429,9 @@ async function createRenderService(o) {
1221
2429
  return;
1222
2430
  } } = o;
1223
2431
  const origins = new Set([].concat(o.origin || []));
1224
- const sign = (kind, body) => crypto2.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
1225
- const dir = (job) => path6.join(folder, job);
1226
- await fsp3.mkdir(folder, { recursive: true });
2432
+ const sign = (kind, body) => crypto6.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
2433
+ const dir = (job) => path12.join(folder, job);
2434
+ await fsp4.mkdir(folder, { recursive: true });
1227
2435
  function readTicket(req) {
1228
2436
  const tk = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
1229
2437
  const [v, body, sig] = tk.split(".");
@@ -1244,7 +2452,7 @@ async function createRenderService(o) {
1244
2452
  const jobs = new Map;
1245
2453
  const queue = [];
1246
2454
  let current = null;
1247
- const persist = (t) => fsp3.writeFile(path6.join(dir(t.job), "status.json"), JSON.stringify(t)).catch(() => {
2455
+ const persist = (t) => fsp4.writeFile(path12.join(dir(t.job), "status.json"), JSON.stringify(t)).catch(() => {
1248
2456
  return;
1249
2457
  });
1250
2458
  const update = (t, patch) => (Object.assign(t, patch, { diperbarui: Date.now() }), void persist(t));
@@ -1263,19 +2471,19 @@ async function createRenderService(o) {
1263
2471
  });
1264
2472
  async function clearFiles(t, all = false) {
1265
2473
  for (const n of all ? ["."] : ["paket", "paket.zip", "profil", "mentah.mp4", "mentah.webm"])
1266
- await fsp3.rm(path6.join(dir(t.job), n), { recursive: true, force: true }).catch(() => {
2474
+ await fsp4.rm(path12.join(dir(t.job), n), { recursive: true, force: true }).catch(() => {
1267
2475
  return;
1268
2476
  });
1269
2477
  if (!all) {
1270
- for (const f of await fsp3.readdir(dir(t.job)).catch(() => []))
2478
+ for (const f of await fsp4.readdir(dir(t.job)).catch(() => []))
1271
2479
  if (/^p\d+$/.test(f))
1272
- await fsp3.rm(path6.join(dir(t.job), f), { force: true });
2480
+ await fsp4.rm(path12.join(dir(t.job), f), { force: true });
1273
2481
  }
1274
2482
  }
1275
2483
  async function openPackage(t) {
1276
2484
  const d = dir(t.job);
1277
2485
  const main = t.tiket.jenis === "klip" ? "klip.json" : "proyek.json";
1278
- const entries = await listZip(path6.join(d, "paket.zip"));
2486
+ const entries = await listZip(path12.join(d, "paket.zip"));
1279
2487
  const names = entries.map((x) => x.name).filter((n) => !n.endsWith("/"));
1280
2488
  if (names.some((n) => n.startsWith("/") || n.includes("..") || n.includes("\\") || n !== main && !/^aset\/[\w-]+$/.test(n)))
1281
2489
  throw new Error(EngineError.BadPackage);
@@ -1283,10 +2491,10 @@ async function createRenderService(o) {
1283
2491
  throw new Error(`Paket tidak berisi ${main}.`);
1284
2492
  if (entries.reduce((a, x) => a + x.size, 0) > maxUnzippedMb * 1048576)
1285
2493
  throw new Error("Isi paket terlalu besar.");
1286
- await extractZip(path6.join(d, "paket.zip"), path6.join(d, "paket"));
1287
- await fsp3.rm(path6.join(d, "paket.zip"), { force: true });
1288
- const j = JSON.parse(await fsp3.readFile(path6.join(d, "paket", main), "utf8"));
1289
- const has = (id) => /^[\w-]+$/.test(id) && fs10.existsSync(path6.join(d, "paket", "aset", id));
2494
+ await extractZip(path12.join(d, "paket.zip"), path12.join(d, "paket"));
2495
+ await fsp4.rm(path12.join(d, "paket.zip"), { force: true });
2496
+ const j = JSON.parse(await fsp4.readFile(path12.join(d, "paket", main), "utf8"));
2497
+ const has = (id) => /^[\w-]+$/.test(id) && fs16.existsSync(path12.join(d, "paket", "aset", id));
1290
2498
  if (main === "klip.json") {
1291
2499
  const k = j.klip || {};
1292
2500
  const seconds = Number(k.durationInFrames) / Number(k.fps);
@@ -1334,7 +2542,7 @@ async function createRenderService(o) {
1334
2542
  job: t.job,
1335
2543
  kind: t.tiket.jenis,
1336
2544
  dir: dir(t.job),
1337
- packageDir: path6.join(dir(t.job), "paket"),
2545
+ packageDir: path12.join(dir(t.job), "paket"),
1338
2546
  transparent: !!t.transparan,
1339
2547
  persen: t.persen,
1340
2548
  width: t.tiket.w,
@@ -1351,10 +2559,10 @@ async function createRenderService(o) {
1351
2559
  const h = await renderer(task, { progress, signal: cancel.signal });
1352
2560
  if (cancel.signal.aborted)
1353
2561
  throw new Error("Dibatalkan.");
1354
- const size = (await fsp3.stat(h.file)).size;
2562
+ const size = (await fsp4.stat(h.file)).size;
1355
2563
  if (size < 200)
1356
2564
  throw new Error(EngineError.EmptyResult);
1357
- update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path6.basename(h.file), hasilJenis: h.type });
2565
+ update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path12.basename(h.file), hasilJenis: h.type });
1358
2566
  onJob("done", t);
1359
2567
  } catch (e) {
1360
2568
  if (t.status !== "batal") {
@@ -1383,7 +2591,7 @@ async function createRenderService(o) {
1383
2591
  }
1384
2592
  const json = (req, res, code, body) => (res.writeHead(code, { ...cors(req), "content-type": "application/json", "cache-control": "no-store" }), res.end(JSON.stringify(body)));
1385
2593
  async function sendFile(req, res, f, type, name) {
1386
- const st = await fsp3.stat(f);
2594
+ const st = await fsp4.stat(f);
1387
2595
  const range = /^bytes=(\d+)-(\d*)$/.exec(String(req.headers.range || ""));
1388
2596
  const h = { ...cors(req), "content-type": type, "accept-ranges": "bytes", "cache-control": "no-store", "content-disposition": `attachment; filename="${name}"` };
1389
2597
  if (range) {
@@ -1392,10 +2600,10 @@ async function createRenderService(o) {
1392
2600
  if (a > z)
1393
2601
  return res.writeHead(416, { ...h, "content-range": `bytes */${st.size}` }), res.end();
1394
2602
  res.writeHead(206, { ...h, "content-length": z - a + 1, "content-range": `bytes ${a}-${z}/${st.size}` });
1395
- return void fs10.createReadStream(f, { start: a, end: z }).pipe(res);
2603
+ return void fs16.createReadStream(f, { start: a, end: z }).pipe(res);
1396
2604
  }
1397
2605
  res.writeHead(200, { ...h, "content-length": st.size });
1398
- fs10.createReadStream(f).pipe(res);
2606
+ fs16.createReadStream(f).pipe(res);
1399
2607
  }
1400
2608
  const ROUTE = /^\/tugas(?:\/(r_[a-f0-9]{16})(\/potongan\/(\d{1,4})|\/mulai|\/hasil)?)?$/;
1401
2609
  const server = http2.createServer(async (req, res) => {
@@ -1422,7 +2630,7 @@ async function createRenderService(o) {
1422
2630
  return json(req, res, 200, summary(t));
1423
2631
  if (queue.length >= maxQueue)
1424
2632
  return json(req, res, 503, { galat: EngineError.QueueFull });
1425
- await fsp3.mkdir(dir(job), { recursive: true });
2633
+ await fsp4.mkdir(dir(job), { recursive: true });
1426
2634
  t = { job, tiket: ticket, status: "unggah", dibuat: Date.now(), diperbarui: Date.now(), terunggah: 0 };
1427
2635
  jobs.set(job, t);
1428
2636
  persist(t);
@@ -1434,15 +2642,15 @@ async function createRenderService(o) {
1434
2642
  if (t.status !== "unggah")
1435
2643
  return json(req, res, 409, { galat: "Unggahan sudah ditutup." });
1436
2644
  const n = Number(m[3]);
1437
- const f = path6.join(dir(job), `p${n}`);
1438
- const before = fs10.existsSync(f) ? (await fsp3.stat(f)).size : 0;
2645
+ const f = path12.join(dir(job), `p${n}`);
2646
+ const before = fs16.existsSync(f) ? (await fsp4.stat(f)).size : 0;
1439
2647
  const room = Number(ticket.maksMb) * 1048576 - (t.terunggah - before);
1440
2648
  const size = await saveBody2(req, f, Math.min(partMb * 1048576 + 1024, room));
1441
2649
  const expected = String(req.headers["x-sha256"] || "").toLowerCase();
1442
2650
  if (expected) {
1443
- const digest = crypto2.createHash("sha256").update(await fsp3.readFile(f)).digest("hex");
2651
+ const digest = crypto6.createHash("sha256").update(await fsp4.readFile(f)).digest("hex");
1444
2652
  if (digest !== expected) {
1445
- await fsp3.rm(f, { force: true });
2653
+ await fsp4.rm(f, { force: true });
1446
2654
  update(t, { terunggah: t.terunggah - before });
1447
2655
  return json(req, res, 400, { galat: "Potongan rusak di jalan. Kirim ulang." });
1448
2656
  }
@@ -1457,24 +2665,24 @@ async function createRenderService(o) {
1457
2665
  const count = Number(b.jumlah);
1458
2666
  if (!(count > 0 && count < 1e4))
1459
2667
  return json(req, res, 400, { galat: "Jumlah potongan tidak valid." });
1460
- const zip = path6.join(dir(job), "paket.zip");
1461
- const out = fs10.createWriteStream(zip);
1462
- const hash = crypto2.createHash("sha256");
2668
+ const zip = path12.join(dir(job), "paket.zip");
2669
+ const out = fs16.createWriteStream(zip);
2670
+ const hash = crypto6.createHash("sha256");
1463
2671
  let total = 0;
1464
2672
  for (let i = 0;i < count; i++) {
1465
- const f = path6.join(dir(job), `p${i}`);
1466
- if (!fs10.existsSync(f))
2673
+ const f = path12.join(dir(job), `p${i}`);
2674
+ if (!fs16.existsSync(f))
1467
2675
  return out.destroy(), json(req, res, 400, { galat: `Potongan ${i + 1} belum terunggah.` });
1468
- const part = await fsp3.readFile(f);
2676
+ const part = await fsp4.readFile(f);
1469
2677
  hash.update(part);
1470
2678
  total += part.length;
1471
2679
  await new Promise((ok) => out.write(part) ? ok() : out.once("drain", ok));
1472
- await fsp3.rm(f, { force: true });
2680
+ await fsp4.rm(f, { force: true });
1473
2681
  }
1474
2682
  await new Promise((ok) => out.end(ok));
1475
2683
  const digest = hash.digest("hex");
1476
2684
  if (total !== Number(b.ukuran) || b.sha256 && digest !== String(b.sha256).toLowerCase()) {
1477
- await fsp3.rm(zip, { force: true });
2685
+ await fsp4.rm(zip, { force: true });
1478
2686
  update(t, { terunggah: 0 });
1479
2687
  return json(req, res, 400, { galat: "Unggahan rusak di jalan. Coba render lagi." });
1480
2688
  }
@@ -1493,8 +2701,8 @@ async function createRenderService(o) {
1493
2701
  return json(req, res, 200, summary(t));
1494
2702
  }
1495
2703
  if (m[2] === "/hasil" && (req.method === "GET" || req.method === "HEAD")) {
1496
- const f = t.hasilBerkas ? path6.join(dir(job), t.hasilBerkas) : "";
1497
- if (t.status !== "selesai" || !f || !fs10.existsSync(f))
2704
+ const f = t.hasilBerkas ? path12.join(dir(job), t.hasilBerkas) : "";
2705
+ if (t.status !== "selesai" || !f || !fs16.existsSync(f))
1498
2706
  return json(req, res, 409, { galat: "Video belum jadi." });
1499
2707
  const webm = t.hasilJenis === "video/webm";
1500
2708
  return sendFile(req, res, f, webm ? "video/webm" : "video/mp4", `hypeframe-${job}.${webm ? "webm" : "mp4"}`);
@@ -1521,16 +2729,16 @@ async function createRenderService(o) {
1521
2729
  json(req, res, 500, { galat: EngineError.ServiceError });
1522
2730
  }
1523
2731
  });
1524
- for (const job of await fsp3.readdir(folder).catch(() => [])) {
2732
+ for (const job of await fsp4.readdir(folder).catch(() => [])) {
1525
2733
  if (!JOB_ID.test(job))
1526
2734
  continue;
1527
2735
  try {
1528
- const t = JSON.parse(await fsp3.readFile(path6.join(dir(job), "status.json"), "utf8"));
2736
+ const t = JSON.parse(await fsp4.readFile(path12.join(dir(job), "status.json"), "utf8"));
1529
2737
  if (t.status === "jalan" || t.status === "antre")
1530
2738
  update(t, { status: "gagal", galat: EngineError.Restarted });
1531
2739
  jobs.set(job, t);
1532
2740
  } catch {
1533
- await fsp3.rm(dir(job), { recursive: true, force: true });
2741
+ await fsp4.rm(dir(job), { recursive: true, force: true });
1534
2742
  }
1535
2743
  }
1536
2744
  const sweep = setInterval(async () => {
@@ -1559,7 +2767,7 @@ async function createRenderService(o) {
1559
2767
  };
1560
2768
  }
1561
2769
 
1562
- // packages/hypeframe/src/ui/banner.ts
2770
+ // src/ui/banner.ts
1563
2771
  function banner() {
1564
2772
  const mark = color.brand("◆");
1565
2773
  return `
@@ -1568,8 +2776,8 @@ function banner() {
1568
2776
  `;
1569
2777
  }
1570
2778
 
1571
- // packages/hypeframe/src/util/format.ts
1572
- function bytes(n) {
2779
+ // src/util/format.ts
2780
+ function bytes2(n) {
1573
2781
  if (!(n > 0))
1574
2782
  return "0 B";
1575
2783
  const units = ["B", "KB", "MB", "GB", "TB"];
@@ -1605,13 +2813,13 @@ function table(rows, indent = " ") {
1605
2813
  `);
1606
2814
  }
1607
2815
 
1608
- // packages/hypeframe/src/util/open.ts
1609
- import { spawn as spawn2 } from "node:child_process";
2816
+ // src/util/open.ts
2817
+ import { spawn as spawn3 } from "node:child_process";
1610
2818
  var PAIRING_LINK = new RegExp(`^https?://[A-Za-z0-9.-]+(:\\d+)?/sambung\\?kode=${PAIRING_CODE.source.slice(1, -1)}$`);
1611
2819
  var WEB_ORIGIN = /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?\/?$/;
1612
2820
  function launch(target) {
1613
2821
  const [cmd, args] = process.platform === "win32" ? ["explorer.exe", [target]] : [process.platform === "darwin" ? "open" : "xdg-open", [target]];
1614
- const p = spawn2(cmd, args, { stdio: "ignore", detached: true });
2822
+ const p = spawn3(cmd, args, { stdio: "ignore", detached: true });
1615
2823
  p.on("error", () => {
1616
2824
  return;
1617
2825
  });
@@ -1627,7 +2835,7 @@ function openFolder(dir) {
1627
2835
  launch(dir);
1628
2836
  }
1629
2837
 
1630
- // packages/hypeframe/src/cli/commands/start.ts
2838
+ // src/cli/commands/start.ts
1631
2839
  async function pairDevice(s, noBrowser = false) {
1632
2840
  const a = await pair({
1633
2841
  gateway: s.gateway,
@@ -1671,8 +2879,16 @@ async function start(args, { fromMenu = false } = {}) {
1671
2879
  account = await pairDevice(s, args.flags.noBrowser);
1672
2880
  else
1673
2881
  log.ok(t("pair.done", { email: color.bold(maskEmail(account.email)) }));
1674
- const capabilities = { render: false, chrome: null, transparan: false };
1675
- const key = crypto3.randomBytes(32).toString("base64url");
2882
+ let conn = null;
2883
+ let servicePort = 0;
2884
+ const agents = createAgentService({
2885
+ 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" }) },
2886
+ port: () => servicePort,
2887
+ bridge: bridgeLaunch(),
2888
+ onToolError: (e) => log.warn(t(e === "tab" ? "agent.toolNoTab" : "agent.toolNoAnswer"))
2889
+ });
2890
+ const capabilities = { render: false, chrome: null, transparan: false, agen: agents.capabilities() };
2891
+ const key = crypto7.randomBytes(32).toString("base64url");
1676
2892
  const cache = cacheDir();
1677
2893
  const page = createPage({ web: s.web, cacheDir: cache });
1678
2894
  let runner = null;
@@ -1682,13 +2898,13 @@ async function start(args, { fromMenu = false } = {}) {
1682
2898
  key,
1683
2899
  origin: new URL(s.web).origin,
1684
2900
  renderer: (task, o) => runner ? runner.renderer(task, o) : Promise.reject(new Error(EngineError.NotReady)),
1685
- extraRoute: (req, res, url) => runner ? runner.route(req, res, url) : page.route(req, res, url),
2901
+ extraRoute: async (req, res, url) => await agents.route(req, res, url) || (runner ? runner.route(req, res, url) : page.route(req, res, url)),
1686
2902
  onJob: (event, j) => {
1687
2903
  if (event === "started") {
1688
2904
  started.set(j.job, Date.now());
1689
2905
  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`) }));
1690
2906
  } else if (event === "done") {
1691
- log.ok(t("render.jobDone", { sec: seconds(Date.now() - (started.get(j.job) ?? Date.now())), size: bytes(j.hasilUkuran ?? 0) }));
2907
+ log.ok(t("render.jobDone", { sec: seconds(Date.now() - (started.get(j.job) ?? Date.now())), size: bytes2(j.hasilUkuran ?? 0) }));
1692
2908
  started.delete(j.job);
1693
2909
  } else if (event === "failed") {
1694
2910
  log.warn(t("render.jobFailed", { reason: j.galat || "?" }));
@@ -1699,17 +2915,28 @@ async function start(args, { fromMenu = false } = {}) {
1699
2915
  }
1700
2916
  }
1701
2917
  });
2918
+ servicePort = service.port;
1702
2919
  const handler = createHandler({
1703
2920
  status: () => ({ versi: VERSION, os: osName(), kemampuan: capabilities }),
1704
2921
  kunci: () => {
1705
2922
  if (!capabilities.render)
1706
2923
  throw new Error(EngineError.NotReady);
1707
2924
  return { port: service.port, kunci: key, versi: VERSION };
1708
- }
2925
+ },
2926
+ ...agents.work
1709
2927
  });
1710
- const conn = new Connection({ gateway: s.gateway, token: account.token, info: { versi: VERSION, os: osName(), nama: s.name, kemampuan: capabilities, portLokal: service.port }, handler });
2928
+ const engineConn = new Connection({ gateway: s.gateway, token: account.token, info: { versi: VERSION, os: osName(), nama: s.name, kemampuan: capabilities, portLokal: service.port }, handler });
2929
+ conn = engineConn;
2930
+ setInterval(() => {
2931
+ const now = agents.capabilities();
2932
+ if (JSON.stringify(now) === JSON.stringify(capabilities.agen))
2933
+ return;
2934
+ capabilities.agen = now;
2935
+ conn?.setInfo({ kemampuan: capabilities });
2936
+ conn?.news("status", { kemampuan: capabilities });
2937
+ }, 30000).unref();
1711
2938
  let connectedBefore = false;
1712
- conn.on("connected", () => {
2939
+ engineConn.on("connected", () => {
1713
2940
  if (connectedBefore)
1714
2941
  log.ok(t("engine.reconnected"));
1715
2942
  else {
@@ -1718,16 +2945,16 @@ async function start(args, { fromMenu = false } = {}) {
1718
2945
  }
1719
2946
  connectedBefore = true;
1720
2947
  });
1721
- conn.on("disconnected", () => log.warn(t("engine.lost")));
1722
- conn.on("revoked", () => {
2948
+ engineConn.on("disconnected", () => log.warn(t("engine.lost")));
2949
+ engineConn.on("revoked", () => {
1723
2950
  log.warn(t("engine.revoked"));
1724
2951
  process.exit(0);
1725
2952
  });
1726
- conn.on("stopped", (reason) => {
2953
+ engineConn.on("stopped", (reason) => {
1727
2954
  log.error(reason === "protocol" ? t("engine.tooOld") : t("engine.replaced"));
1728
2955
  process.exit(1);
1729
2956
  });
1730
- conn.start();
2957
+ engineConn.start();
1731
2958
  let lastPercent = -10;
1732
2959
  const chromeProgress = (percent, what) => {
1733
2960
  if (percent === 0)
@@ -1740,18 +2967,22 @@ async function start(args, { fromMenu = false } = {}) {
1740
2967
  };
1741
2968
  async function prepareRender() {
1742
2969
  try {
1743
- if (!ffmpegPath)
1744
- throw new Error(t("doctor.noFfmpeg"));
2970
+ const ffmpeg = await prepareFfmpeg(cache, (percent) => {
2971
+ if (percent === 0)
2972
+ log.info(t("render.downloadingFfmpeg"));
2973
+ else
2974
+ log.detail(`ffmpeg ${percent}%`);
2975
+ });
1745
2976
  const chrome = await prepareChrome(cache, chromeProgress);
1746
2977
  const info = await checkChrome(chrome, { gpu: s.gpu });
1747
2978
  if (!info.avc)
1748
2979
  throw new Error(t("render.noH264", { chrome: info.version }));
1749
2980
  await page.prepare();
1750
- runner = createJobRunner({ chrome, ffmpeg: ffmpegPath, page, gpu: s.gpu, transparent: info.transparent, note: (m) => log.detail(m) });
2981
+ runner = createJobRunner({ chrome, ffmpeg, page, gpu: s.gpu, transparent: info.transparent, note: (m) => log.detail(m) });
1751
2982
  runner.setPort(service.port);
1752
2983
  Object.assign(capabilities, { render: true, chrome: info.version, transparan: info.transparent });
1753
- conn.setInfo({ kemampuan: capabilities });
1754
- conn.news("status", { kemampuan: capabilities });
2984
+ engineConn.setInfo({ kemampuan: capabilities });
2985
+ engineConn.news("status", { kemampuan: capabilities });
1755
2986
  log.ok(t("render.ready", { chrome: info.version, extra: info.transparent ? "" : t("render.noAlpha") }));
1756
2987
  } catch (e) {
1757
2988
  log.warn(t("render.notYet", { reason: e.message }));
@@ -1765,8 +2996,8 @@ async function start(args, { fromMenu = false } = {}) {
1765
2996
  const stop = () => {
1766
2997
  console.log("");
1767
2998
  log.info(t("engine.stopped"));
1768
- conn.stop();
1769
- service.stop().finally(() => process.exit(0));
2999
+ engineConn.stop();
3000
+ Promise.all([service.stop(), agents.stop()]).finally(() => process.exit(0));
1770
3001
  setTimeout(() => process.exit(0), 2000).unref();
1771
3002
  };
1772
3003
  process.once("SIGINT", stop);
@@ -1776,7 +3007,7 @@ async function start(args, { fromMenu = false } = {}) {
1776
3007
  });
1777
3008
  }
1778
3009
 
1779
- // packages/hypeframe/src/cli/commands/account.ts
3010
+ // src/cli/commands/account.ts
1780
3011
  async function login(args) {
1781
3012
  const s = resolveSettings(args.flags);
1782
3013
  const a = readAccount();
@@ -1792,33 +3023,25 @@ function logout() {
1792
3023
  log.ok(t("logout.done"));
1793
3024
  }
1794
3025
 
1795
- // packages/hypeframe/src/cli/commands/autostart.ts
1796
- import { spawnSync } from "node:child_process";
1797
- import fs11 from "node:fs";
3026
+ // src/cli/commands/autostart.ts
3027
+ import { spawnSync as spawnSync2 } from "node:child_process";
3028
+ import fs17 from "node:fs";
1798
3029
  import os3 from "node:os";
1799
- import path7 from "node:path";
3030
+ import path13 from "node:path";
1800
3031
  function entryFile() {
1801
3032
  const home = os3.homedir();
1802
3033
  if (process.platform === "win32")
1803
- return path7.join(process.env.APPDATA || path7.join(home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "HypeFrame.cmd");
3034
+ return path13.join(process.env.APPDATA || path13.join(home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "HypeFrame.cmd");
1804
3035
  if (process.platform === "darwin")
1805
- return path7.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
3036
+ return path13.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
1806
3037
  if (hasSystemd())
1807
- return path7.join(home, ".config", "systemd", "user", "hypeframe.service");
1808
- return path7.join(home, ".config", "autostart", "hypeframe.desktop");
3038
+ return path13.join(home, ".config", "systemd", "user", "hypeframe.service");
3039
+ return path13.join(home, ".config", "autostart", "hypeframe.desktop");
1809
3040
  }
1810
3041
  function hasSystemd() {
1811
- return process.platform === "linux" && spawnSync("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
3042
+ return process.platform === "linux" && spawnSync2("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
1812
3043
  }
1813
- function installedScript() {
1814
- try {
1815
- const script = fs11.realpathSync(process.argv[1] || "");
1816
- return /[\\/]_npx[\\/]/.test(script) ? null : script;
1817
- } catch {
1818
- return null;
1819
- }
1820
- }
1821
- var autostartEnabled = () => fs11.existsSync(entryFile());
3044
+ var autostartEnabled = () => fs17.existsSync(entryFile());
1822
3045
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1823
3046
  function autostart(mode) {
1824
3047
  const file = entryFile();
@@ -1829,59 +3052,59 @@ function autostart(mode) {
1829
3052
  }
1830
3053
  if (mode === "off") {
1831
3054
  if (process.platform === "linux" && file.endsWith(".service"))
1832
- spawnSync("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
1833
- fs11.rmSync(file, { force: true });
3055
+ spawnSync2("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
3056
+ fs17.rmSync(file, { force: true });
1834
3057
  log.ok(t("autostart.off"));
1835
3058
  return;
1836
3059
  }
1837
- const script = installedScript();
1838
- if (!script) {
3060
+ const cmd = launchCommand();
3061
+ if (!cmd) {
1839
3062
  log.warn(t("autostart.needGlobal"));
1840
- log.detail("npm i -g hypeframe");
3063
+ log.detail(`curl -fsSL ${INSTALL_URL} | bash`);
1841
3064
  return;
1842
3065
  }
1843
3066
  if (!readAccount()) {
1844
3067
  log.warn(t("autostart.needLogin"));
1845
3068
  return;
1846
3069
  }
1847
- const node = process.execPath;
1848
- fs11.mkdirSync(path7.dirname(file), { recursive: true });
3070
+ const quoted = cmd.map((c) => `"${c}"`).join(" ");
3071
+ fs17.mkdirSync(path13.dirname(file), { recursive: true });
1849
3072
  if (process.platform === "win32") {
1850
- fs11.writeFileSync(file, `@echo off\r
1851
- start "HypeFrame" /min "${node}" "${script}" start --no-browser\r
3073
+ fs17.writeFileSync(file, `@echo off\r
3074
+ start "HypeFrame" /min ${quoted} start --no-browser\r
1852
3075
  `);
1853
3076
  } else if (process.platform === "darwin") {
1854
- const out = path7.join(logDir(), "autostart.log");
1855
- fs11.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
3077
+ const out = path13.join(logDir(), "autostart.log");
3078
+ fs17.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
1856
3079
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1857
3080
  <plist version="1.0"><dict>
1858
3081
  <key>Label</key><string>com.hypeframe.engine</string>
1859
- <key>ProgramArguments</key><array><string>${xml(node)}</string><string>${xml(script)}</string><string>start</string><string>--no-browser</string></array>
3082
+ <key>ProgramArguments</key><array>${cmd.map((c) => `<string>${xml(c)}</string>`).join("")}<string>start</string><string>--no-browser</string></array>
1860
3083
  <key>RunAtLoad</key><true/>
1861
3084
  <key>StandardOutPath</key><string>${xml(out)}</string>
1862
3085
  <key>StandardErrorPath</key><string>${xml(out)}</string>
1863
3086
  </dict></plist>
1864
3087
  `);
1865
3088
  } else if (file.endsWith(".service")) {
1866
- fs11.writeFileSync(file, `[Unit]
3089
+ fs17.writeFileSync(file, `[Unit]
1867
3090
  Description=HypeFrame engine
1868
3091
  After=network-online.target
1869
3092
 
1870
3093
  [Service]
1871
- ExecStart="${node}" "${script}" start --no-browser
3094
+ ExecStart=${quoted} start --no-browser
1872
3095
  Restart=on-failure
1873
3096
  RestartSec=60
1874
3097
 
1875
3098
  [Install]
1876
3099
  WantedBy=default.target
1877
3100
  `);
1878
- spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
1879
- spawnSync("systemctl", ["--user", "enable", "hypeframe.service"], { stdio: "ignore" });
3101
+ spawnSync2("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
3102
+ spawnSync2("systemctl", ["--user", "enable", "hypeframe.service"], { stdio: "ignore" });
1880
3103
  } else {
1881
- fs11.writeFileSync(file, `[Desktop Entry]
3104
+ fs17.writeFileSync(file, `[Desktop Entry]
1882
3105
  Type=Application
1883
3106
  Name=HypeFrame engine
1884
- Exec="${node}" "${script}" start --no-browser
3107
+ Exec=${quoted} start --no-browser
1885
3108
  Terminal=false
1886
3109
  X-GNOME-Autostart-enabled=true
1887
3110
  `);
@@ -1890,7 +3113,7 @@ X-GNOME-Autostart-enabled=true
1890
3113
  log.detail(file);
1891
3114
  }
1892
3115
 
1893
- // packages/hypeframe/src/cli/commands/bench.ts
3116
+ // src/cli/commands/bench.ts
1894
3117
  import http3 from "node:http";
1895
3118
  import puppeteer3 from "puppeteer-core";
1896
3119
  var FRAMES = 150;
@@ -1976,8 +3199,377 @@ async function bench(args) {
1976
3199
  `);
1977
3200
  }
1978
3201
 
1979
- // packages/hypeframe/src/cli/commands/config.ts
3202
+ // src/cli/commands/agent.ts
1980
3203
  import * as p from "@clack/prompts";
3204
+
3205
+ // src/agent/install.ts
3206
+ import fs18 from "node:fs";
3207
+ import fsp5 from "node:fs/promises";
3208
+ import path14 from "node:path";
3209
+ import yauzl2 from "yauzl";
3210
+ function unzip(file, to) {
3211
+ return new Promise((ok, fail) => {
3212
+ yauzl2.open(file, { lazyEntries: true }, (e, zip) => {
3213
+ if (e || !zip)
3214
+ return fail(e ?? new Error("zip"));
3215
+ zip.on("entry", (en) => {
3216
+ const target = path14.join(to, en.fileName);
3217
+ if (!target.startsWith(to + path14.sep))
3218
+ return fail(new Error("archive path outside the agent folder"));
3219
+ if (en.fileName.endsWith("/"))
3220
+ return fs18.mkdirSync(target, { recursive: true }), zip.readEntry();
3221
+ fs18.mkdirSync(path14.dirname(target), { recursive: true });
3222
+ zip.openReadStream(en, (e2, s) => {
3223
+ if (e2 || !s)
3224
+ return fail(e2 ?? new Error("zip"));
3225
+ const out = fs18.createWriteStream(target);
3226
+ s.pipe(out);
3227
+ out.on("finish", () => zip.readEntry());
3228
+ out.on("error", fail);
3229
+ });
3230
+ });
3231
+ zip.on("end", () => ok());
3232
+ zip.on("error", fail);
3233
+ zip.readEntry();
3234
+ });
3235
+ });
3236
+ }
3237
+ async function untarGz(file, to) {
3238
+ const { gunzipSync } = await import("node:zlib");
3239
+ const data = gunzipSync(await fsp5.readFile(file));
3240
+ const root = path14.resolve(to);
3241
+ const str = (b) => b.toString("utf8").replace(/\0[\s\S]*$/, "");
3242
+ const octal = (b) => Number.parseInt(str(b).trim() || "0", 8) || 0;
3243
+ let off = 0;
3244
+ let longName = null;
3245
+ while (off + 512 <= data.length) {
3246
+ const h = data.subarray(off, off + 512);
3247
+ if (h.every((x) => x === 0))
3248
+ break;
3249
+ const size = octal(h.subarray(124, 136));
3250
+ const type = String.fromCharCode(h[156] || 48);
3251
+ const body = data.subarray(off + 512, off + 512 + size);
3252
+ off += 512 + Math.ceil(size / 512) * 512;
3253
+ const prefix = str(h.subarray(345, 500));
3254
+ let name = longName ?? (prefix ? `${prefix}/${str(h.subarray(0, 100))}` : str(h.subarray(0, 100)));
3255
+ longName = null;
3256
+ if (type === "x") {
3257
+ const m = body.toString("utf8").match(/(?:^|\n)\d+ path=([^\n]*)\n/);
3258
+ if (m)
3259
+ longName = m[1];
3260
+ continue;
3261
+ }
3262
+ if (type === "L") {
3263
+ longName = str(body);
3264
+ continue;
3265
+ }
3266
+ if (type === "g")
3267
+ continue;
3268
+ name = name.replace(/^\.\//, "");
3269
+ if (!name)
3270
+ continue;
3271
+ const target = path14.resolve(root, name);
3272
+ if (target !== root && !target.startsWith(root + path14.sep))
3273
+ throw new Error("archive path outside the agent folder");
3274
+ if (type === "5") {
3275
+ await fsp5.mkdir(target, { recursive: true });
3276
+ continue;
3277
+ }
3278
+ if (type !== "0" && type !== "7")
3279
+ continue;
3280
+ await fsp5.mkdir(path14.dirname(target), { recursive: true });
3281
+ await fsp5.writeFile(target, body, { mode: octal(h.subarray(100, 108)) & 73 ? 493 : 420 });
3282
+ }
3283
+ }
3284
+ function npxRunner(pkg, extra = []) {
3285
+ if (isStandalone())
3286
+ return { cmd: process.execPath, args: ["x", pkg, ...extra], env: { BUN_BE_BUN: "1" } };
3287
+ const npxCli = path14.join(path14.dirname(process.execPath), process.platform === "win32" ? "" : "..", process.platform === "win32" ? "node_modules" : "lib/node_modules", "npm", "bin", "npx-cli.js");
3288
+ if (!fs18.existsSync(npxCli))
3289
+ throw new Error("npx was not found next to Node.js");
3290
+ return { cmd: process.execPath, args: [npxCli, "-y", pkg, ...extra], env: {} };
3291
+ }
3292
+ function onPath(name) {
3293
+ if (!/^[\w.@+-]{1,80}$/.test(name))
3294
+ return null;
3295
+ const file = process.platform === "win32" ? /\.exe$/i.test(name) ? name : `${name}.exe` : name;
3296
+ for (const dir of (process.env.PATH || "").split(path14.delimiter).filter(Boolean)) {
3297
+ const f = path14.join(dir, file);
3298
+ try {
3299
+ const st = fs18.statSync(f);
3300
+ if (st.isFile() && (process.platform === "win32" || st.mode & 73))
3301
+ return f;
3302
+ } catch {}
3303
+ }
3304
+ return null;
3305
+ }
3306
+ function ownCopy(a) {
3307
+ const bin = a.distribution.binary?.[platformKey()];
3308
+ if (bin) {
3309
+ const cmd = onPath(path14.basename(bin.cmd).replace(/\.exe$/i, ""));
3310
+ return cmd ? { cmd, args: bin.args ?? [], env: bin.env ?? {} } : null;
3311
+ }
3312
+ const npx = a.distribution.npx;
3313
+ if (npx) {
3314
+ const name = npx.package.replace(/(?!^)@[^@/]*$/, "").split("/").pop() ?? "";
3315
+ const cmd = onPath(name);
3316
+ return cmd ? { cmd, args: npx.args ?? [], env: npx.env ?? {} } : null;
3317
+ }
3318
+ return null;
3319
+ }
3320
+ async function installAgent(id, progress = () => {
3321
+ return;
3322
+ }, opts = {}) {
3323
+ const a = (await fetchRegistry()).find((x) => x.id === id);
3324
+ if (!a)
3325
+ throw new Error(`Agent ${id} is not in the registry`);
3326
+ const local = a.distribution.local;
3327
+ if (!isSupported(id) && !local)
3328
+ throw new Error(`Agent ${id} is not supported`);
3329
+ let launch;
3330
+ const bin = a.distribution.binary?.[platformKey()];
3331
+ const own = local || opts.download ? null : ownCopy(a);
3332
+ if (local) {
3333
+ launch = { cmd: local.cmd, args: local.args ?? [], env: {} };
3334
+ } else if (own) {
3335
+ launch = own;
3336
+ } else if (bin) {
3337
+ if (!/^[0-9a-f]{64}$/i.test(bin.sha256 || ""))
3338
+ throw new Error(`Agent ${id}: the registry gives no sha256; not installed`);
3339
+ const dir = path14.join(agentDir(), id, a.version);
3340
+ const tmp = `${dir}.tmp`;
3341
+ await fsp5.rm(tmp, { recursive: true, force: true });
3342
+ await fsp5.mkdir(tmp, { recursive: true });
3343
+ try {
3344
+ const name = path14.basename(new URL(bin.archive).pathname);
3345
+ const cmdRel = bin.cmd.replace(/^\.\//, "");
3346
+ if (/\.zip$/i.test(name)) {
3347
+ const file = path14.join(tmp, ".download.zip");
3348
+ await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
3349
+ await unzip(file, tmp);
3350
+ await fsp5.rm(file, { force: true });
3351
+ } else if (/\.(tar\.gz|tgz)$/i.test(name)) {
3352
+ const file = path14.join(tmp, ".download.tar.gz");
3353
+ await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
3354
+ await untarGz(file, tmp);
3355
+ await fsp5.rm(file, { force: true });
3356
+ } else if (/\.gz$/i.test(name)) {
3357
+ await downloadVerified(bin.archive, bin.sha256.toLowerCase(), path14.join(tmp, cmdRel), progress, true);
3358
+ } else
3359
+ throw new Error(`Agent ${id}: unsupported archive ${name}`);
3360
+ const cmd = path14.join(tmp, cmdRel);
3361
+ if (!fs18.existsSync(cmd))
3362
+ throw new Error(`Agent ${id}: ${bin.cmd} is not in the download`);
3363
+ if (process.platform !== "win32")
3364
+ await fsp5.chmod(cmd, 493);
3365
+ await fsp5.rm(dir, { recursive: true, force: true });
3366
+ await fsp5.rename(tmp, dir);
3367
+ launch = { cmd: path14.join(dir, cmdRel), args: bin.args ?? [], env: bin.env ?? {} };
3368
+ } catch (e) {
3369
+ await fsp5.rm(tmp, { recursive: true, force: true });
3370
+ throw e;
3371
+ }
3372
+ } else if (a.distribution.npx) {
3373
+ launch = { ...npxRunner(a.distribution.npx.package, a.distribution.npx.args), env: { ...a.distribution.npx.env ?? {} } };
3374
+ if (isStandalone())
3375
+ launch.env.BUN_BE_BUN = "1";
3376
+ } else
3377
+ throw new Error(`Agent ${id} has no download for ${platformKey()}`);
3378
+ const installed = { id, name: a.name, version: a.version, launch, ...own ? { own: true } : {} };
3379
+ writeInstalled(installed);
3380
+ return installed;
3381
+ }
3382
+
3383
+ // src/agent/login.ts
3384
+ import { spawnSync as spawnSync3 } from "node:child_process";
3385
+ async function keyFromShell(name, io) {
3386
+ const value = process.env[name];
3387
+ if (!value)
3388
+ return null;
3389
+ if (io.confirm)
3390
+ return await io.confirm(t("agent.keyFromShellAsk", { name })) ? value : null;
3391
+ io.say(t("agent.keyFromShell", { name }));
3392
+ return value;
3393
+ }
3394
+ var API_KEY_ONLY = { "claude-acp": "ANTHROPIC_API_KEY" };
3395
+ async function checkReady(id) {
3396
+ const a = readInstalled().find((x) => x.id === id);
3397
+ if (!a)
3398
+ return false;
3399
+ const proc = new AcpProcess;
3400
+ try {
3401
+ await proc.start(a, projectDir("_cek"), agentEnv(id));
3402
+ await proc.request("session/new", { cwd: projectDir("_cek"), mcpServers: [] }, 90000);
3403
+ setReady(id, true);
3404
+ return true;
3405
+ } catch {
3406
+ setReady(id, false);
3407
+ return false;
3408
+ } finally {
3409
+ await proc.stop();
3410
+ }
3411
+ }
3412
+ function pick(methods) {
3413
+ return methods.find((m) => m.type === "terminal") ?? methods.find((m) => m.type === "env_var" || !!m.varName) ?? methods.find((m) => !m.type || m.type === "agent");
3414
+ }
3415
+ async function loginAgent(id, io) {
3416
+ const a = readInstalled().find((x) => x.id === id);
3417
+ if (!a)
3418
+ throw new Error(`Agent ${id} is not installed`);
3419
+ const onlyKey = API_KEY_ONLY[id];
3420
+ if (onlyKey) {
3421
+ const value = await keyFromShell(onlyKey, io) || await io.ask(onlyKey);
3422
+ if (!value)
3423
+ return false;
3424
+ saveAgentEnv(id, { [onlyKey]: value.trim() });
3425
+ return checkReady(id);
3426
+ }
3427
+ const proc = new AcpProcess;
3428
+ let method;
3429
+ try {
3430
+ const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
3431
+ method = pick(init.authMethods ?? []);
3432
+ if (method && (!method.type || method.type === "agent"))
3433
+ await proc.request("authenticate", { methodId: method.id }, 10 * 60000);
3434
+ } finally {
3435
+ await proc.stop();
3436
+ }
3437
+ if (method?.type === "terminal") {
3438
+ io.say(method.name || method.description || id);
3439
+ const r = spawnSync3(a.launch.cmd, [...a.launch.args, ...method.args ?? []], { stdio: "inherit", env: { ...process.env, ...a.launch.env, ...agentEnv(id), ...method.env ?? {} } });
3440
+ if (r.status !== 0)
3441
+ return setReady(id, false), false;
3442
+ } else if (method && (method.type === "env_var" || method.varName)) {
3443
+ const name = method.varName || method.id;
3444
+ const value = await keyFromShell(name, io) || await io.ask(name);
3445
+ if (!value)
3446
+ return false;
3447
+ saveAgentEnv(id, { [name]: value.trim() });
3448
+ }
3449
+ return checkReady(id);
3450
+ }
3451
+
3452
+ // src/cli/commands/agent.ts
3453
+ var NAMES = { "claude-acp": "Claude Code", "antigravity-acp": "Antigravity", "codex-acp": "Codex", opencode: "OpenCode" };
3454
+ var agentName = (id) => NAMES[id] ?? readInstalled().find((a) => a.id === id)?.name ?? id;
3455
+ function agentState(id) {
3456
+ const a = readInstalled().find((x) => x.id === id);
3457
+ return !a ? "none" : a.ready ? "ready" : "login";
3458
+ }
3459
+ var stateText = (s) => s === "ready" ? color.ok(t("agent.ready")) : s === "login" ? color.warn(t("agent.needLogin")) : color.muted(t("agent.notInstalled"));
3460
+ var io = {
3461
+ ask: async (label) => {
3462
+ if (!process.stdin.isTTY)
3463
+ return null;
3464
+ const v = await p.password({ message: t("agent.askKey", { name: label }) });
3465
+ return p.isCancel(v) || !v ? null : String(v);
3466
+ },
3467
+ say: (s) => log.info(s),
3468
+ ...process.stdin.isTTY ? {
3469
+ confirm: async (question) => {
3470
+ const v = await p.confirm({ message: question });
3471
+ return !p.isCancel(v) && v === true;
3472
+ }
3473
+ } : {}
3474
+ };
3475
+ function ids() {
3476
+ return [...new Set([...SUPPORTED_AGENTS, ...readInstalled().map((a) => a.id)])];
3477
+ }
3478
+ function listAgents() {
3479
+ console.log("");
3480
+ const info = (id) => {
3481
+ const a = readInstalled().find((x) => x.id === id);
3482
+ return a ? color.muted(` ${icon.dot} ${a.own ? t("agent.ownTag") : a.version}`) : "";
3483
+ };
3484
+ console.log(table(ids().map((id) => [color.muted(agentName(id)), `${stateText(agentState(id))}${info(id)}`])));
3485
+ console.log(`
3486
+ ${color.muted(t("agent.webHint"))}
3487
+ `);
3488
+ }
3489
+ async function addAgent(id, download = false) {
3490
+ const known = isSupported(id) || (await fetchRegistry()).some((a) => a.id === id && a.distribution.local);
3491
+ if (!known)
3492
+ return log.error(t("agent.unknown", { id, list: SUPPORTED_AGENTS.join(", ") })), false;
3493
+ log.info(t("agent.installing", { name: agentName(id) }));
3494
+ let last = -10;
3495
+ const a = await installAgent(id, (pc) => {
3496
+ if (pc - last >= 20)
3497
+ last = pc, log.detail(`${pc}%`);
3498
+ }, { download });
3499
+ if (a.own)
3500
+ log.ok(t("agent.own", { name: a.name, path: a.launch.cmd }));
3501
+ else
3502
+ log.ok(t("agent.installed", { name: a.name, version: a.version }));
3503
+ const ok = await loginOne(id);
3504
+ if (!ok && a.own)
3505
+ log.detail(t("agent.ownFailed", { name: a.name, id }));
3506
+ return ok;
3507
+ }
3508
+ async function loginOne(id) {
3509
+ if (id === "claude-acp")
3510
+ log.detail(t("agent.claudeKey"));
3511
+ log.info(t("agent.loggingIn", { name: agentName(id) }));
3512
+ const ok = await loginAgent(id, io);
3513
+ if (ok)
3514
+ log.ok(t("agent.loggedIn", { name: agentName(id) }));
3515
+ else
3516
+ log.warn(t("agent.loginFailed", { name: agentName(id) }));
3517
+ return ok;
3518
+ }
3519
+ async function agentCommand(args) {
3520
+ const [sub, id] = args.rest;
3521
+ if (!sub || sub === "list")
3522
+ return listAgents();
3523
+ if (!id)
3524
+ return log.error("hypeframe agent add|login|remove <id>");
3525
+ if (sub === "add")
3526
+ return void await addAgent(id, args.flags.download === true);
3527
+ if (sub === "login") {
3528
+ if (agentState(id) === "none")
3529
+ return log.error(t("agent.notInstalledYet", { name: agentName(id) }));
3530
+ return void await loginOne(id);
3531
+ }
3532
+ if (sub === "remove") {
3533
+ removeAgent(id);
3534
+ return log.ok(t("agent.removed", { name: agentName(id) }));
3535
+ }
3536
+ log.error("hypeframe agent list|add|login|remove <id>");
3537
+ }
3538
+ async function agentMenu() {
3539
+ for (;; ) {
3540
+ const choice = await p.select({
3541
+ message: t("agent.menuQuestion"),
3542
+ 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")) }]
3543
+ });
3544
+ if (p.isCancel(choice) || !choice)
3545
+ return;
3546
+ const state = agentState(choice);
3547
+ const action = await p.select({
3548
+ message: agentName(choice),
3549
+ options: [
3550
+ ...state === "none" ? [{ value: "add", label: t("agent.add") }] : [],
3551
+ ...state !== "none" ? [{ value: "login", label: t("agent.login") }] : [],
3552
+ ...state !== "none" ? [{ value: "remove", label: t("agent.remove") }] : [],
3553
+ { value: "", label: color.muted(t("agent.back")) }
3554
+ ]
3555
+ });
3556
+ if (p.isCancel(action) || !action)
3557
+ continue;
3558
+ try {
3559
+ if (action === "add")
3560
+ await addAgent(choice);
3561
+ if (action === "login")
3562
+ await loginOne(choice);
3563
+ if (action === "remove")
3564
+ removeAgent(choice), log.ok(t("agent.removed", { name: agentName(choice) }));
3565
+ } catch (e) {
3566
+ log.error(e.message);
3567
+ }
3568
+ }
3569
+ }
3570
+
3571
+ // src/cli/commands/config.ts
3572
+ import * as p2 from "@clack/prompts";
1981
3573
  function print() {
1982
3574
  const s = resolveSettings();
1983
3575
  const saved = readSettings();
@@ -2019,13 +3611,13 @@ async function config(args) {
2019
3611
  if (!process.stdin.isTTY || !process.stdout.isTTY)
2020
3612
  return print();
2021
3613
  const s = resolveSettings();
2022
- const name = await p.text({ message: t("config.name"), initialValue: s.name, validate: (v) => v && v.trim() ? undefined : "—" });
2023
- if (p.isCancel(name))
3614
+ const name = await p2.text({ message: t("config.name"), initialValue: s.name, validate: (v) => v && v.trim() ? undefined : "—" });
3615
+ if (p2.isCancel(name))
2024
3616
  return;
2025
- const gpu = await p.confirm({ message: t("config.gpu"), initialValue: s.gpu });
2026
- if (p.isCancel(gpu))
3617
+ const gpu = await p2.confirm({ message: t("config.gpu"), initialValue: s.gpu });
3618
+ if (p2.isCancel(gpu))
2027
3619
  return;
2028
- const language = await p.select({
3620
+ const language = await p2.select({
2029
3621
  message: t("config.language"),
2030
3622
  initialValue: readSettings().language ?? "auto",
2031
3623
  options: [
@@ -2034,7 +3626,7 @@ async function config(args) {
2034
3626
  { value: "en", label: "English" }
2035
3627
  ]
2036
3628
  });
2037
- if (p.isCancel(language))
3629
+ if (p2.isCancel(language))
2038
3630
  return;
2039
3631
  saveSettings({ name: String(name).trim().slice(0, 40), gpu: !!gpu, language });
2040
3632
  resetLang();
@@ -2042,11 +3634,10 @@ async function config(args) {
2042
3634
  log.detail(t("config.restart"));
2043
3635
  }
2044
3636
 
2045
- // packages/hypeframe/src/cli/commands/doctor.ts
2046
- import { spawnSync as spawnSync2 } from "node:child_process";
2047
- import fs12 from "node:fs";
2048
- import path8 from "node:path";
2049
- import ffmpegPath2 from "ffmpeg-static";
3637
+ // src/cli/commands/doctor.ts
3638
+ import { spawnSync as spawnSync4 } from "node:child_process";
3639
+ import fs19 from "node:fs";
3640
+ import path15 from "node:path";
2050
3641
  var mark = { ok: color.ok(icon.ok), warn: color.warn(icon.warn), error: color.error(icon.error) };
2051
3642
  async function reach(url) {
2052
3643
  const t0 = Date.now();
@@ -2068,23 +3659,28 @@ async function doctor(args) {
2068
3659
  console.log(`
2069
3660
  ${color.bold(t("doctor.title"))}
2070
3661
  `);
2071
- const [maj, min] = process.versions.node.split(".").map(Number);
2072
- 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")}` : ""}` });
3662
+ if (isStandalone())
3663
+ show({ label: "Runtime", result: "ok", detail: runtimeLabel() });
3664
+ else {
3665
+ const [maj, min] = process.versions.node.split(".").map(Number);
3666
+ 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")}` : ""}` });
3667
+ }
2073
3668
  try {
2074
- const probe = path8.join(dataDir(), `.probe-${process.pid}`);
2075
- fs12.writeFileSync(probe, "x");
2076
- fs12.rmSync(probe);
2077
- const st = fs12.statfsSync(dataDir());
3669
+ const probe = path15.join(dataDir(), `.probe-${process.pid}`);
3670
+ fs19.writeFileSync(probe, "x");
3671
+ fs19.rmSync(probe);
3672
+ const st = fs19.statfsSync(dataDir());
2078
3673
  const free = st.bavail * st.bsize;
2079
- show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size: bytes(free) })}` });
3674
+ show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size: bytes2(free) })}` });
2080
3675
  } catch (e) {
2081
3676
  show({ label: t("doctor.disk"), result: "error", detail: e.message });
2082
3677
  }
2083
- const ff = ffmpegPath2;
2084
- if (!ff || !fs12.existsSync(ff))
2085
- show({ label: "ffmpeg", result: "error", detail: t("doctor.noFfmpeg") });
2086
- else {
2087
- const r = spawnSync2(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
3678
+ const ff = await findFfmpeg(cacheDir());
3679
+ if (!ff) {
3680
+ const canDownload = !!FFMPEG_PINNED[`${process.platform}-${process.arch}`];
3681
+ show({ label: "ffmpeg", result: canDownload ? "warn" : "error", detail: canDownload ? t("doctor.ffmpegLater") : t("doctor.noFfmpeg") });
3682
+ } else {
3683
+ const r = spawnSync4(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
2088
3684
  const v = /ffmpeg version (\S+)/.exec(r.stdout || "")?.[1];
2089
3685
  show({ label: "ffmpeg", result: v ? "ok" : "error", detail: v || t("doctor.noFfmpeg") });
2090
3686
  }
@@ -2116,22 +3712,22 @@ async function doctor(args) {
2116
3712
  return checks;
2117
3713
  }
2118
3714
 
2119
- // packages/hypeframe/src/cli/commands/history.ts
2120
- import fs13 from "node:fs";
2121
- import path9 from "node:path";
2122
- function readHistory(hours = 24) {
3715
+ // src/cli/commands/history.ts
3716
+ import fs20 from "node:fs";
3717
+ import path16 from "node:path";
3718
+ function readHistory2(hours = 24) {
2123
3719
  const root = renderDir();
2124
3720
  const since = Date.now() - hours * 3600000;
2125
3721
  const out = [];
2126
- for (const name of fs13.readdirSync(root)) {
3722
+ for (const name of fs20.readdirSync(root)) {
2127
3723
  if (!JOB_ID.test(name))
2128
3724
  continue;
2129
3725
  try {
2130
- const j = JSON.parse(fs13.readFileSync(path9.join(root, name, "status.json"), "utf8"));
3726
+ const j = JSON.parse(fs20.readFileSync(path16.join(root, name, "status.json"), "utf8"));
2131
3727
  if ((j.diperbarui || j.dibuat) < since)
2132
3728
  continue;
2133
- const f = j.hasilBerkas ? path9.join(root, name, j.hasilBerkas) : null;
2134
- out.push({ job: j, file: f && fs13.existsSync(f) ? f : null });
3729
+ const f = j.hasilBerkas ? path16.join(root, name, j.hasilBerkas) : null;
3730
+ out.push({ job: j, file: f && fs20.existsSync(f) ? f : null });
2135
3731
  } catch {}
2136
3732
  }
2137
3733
  return out.sort((a, b) => (b.job.diperbarui || 0) - (a.job.diperbarui || 0));
@@ -2141,12 +3737,12 @@ function formatItem({ job: j, file }) {
2141
3737
  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);
2142
3738
  const kind = j.tiket.jenis === "klip" ? t("render.kindClip") : t("render.kindVideo");
2143
3739
  const took = j.selesaiPada && j.mulaiPada ? ` ${color.muted(icon.dot)} ${seconds(j.selesaiPada - j.mulaiPada)}` : "";
2144
- const detail = j.status === "selesai" ? `${bytes(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}%`);
3740
+ 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}%`);
2145
3741
  return `${color.muted(time2(j.diperbarui || j.dibuat))} ${mark} ${kind} ${color.muted(`${j.tiket.w}×${j.tiket.h}`)} ${detail}${file ? `
2146
3742
  ${color.muted(icon.detail)} ${color.muted(file)}` : ""}`;
2147
3743
  }
2148
3744
  function history() {
2149
- const items = readHistory();
3745
+ const items = readHistory2();
2150
3746
  console.log("");
2151
3747
  if (!items.length)
2152
3748
  console.log(` ${color.muted(t("history.empty"))}`);
@@ -2156,41 +3752,41 @@ function history() {
2156
3752
  return items;
2157
3753
  }
2158
3754
 
2159
- // packages/hypeframe/src/cli/commands/maintenance.ts
2160
- import { spawnSync as spawnSync3 } from "node:child_process";
2161
- import fs14 from "node:fs";
3755
+ // src/cli/commands/maintenance.ts
3756
+ import { spawnSync as spawnSync5 } from "node:child_process";
3757
+ import fs21 from "node:fs";
2162
3758
  import os4 from "node:os";
2163
- import path10 from "node:path";
3759
+ import path17 from "node:path";
2164
3760
  async function clean() {
2165
3761
  if (runningPid()) {
2166
3762
  log.warn(t("clean.running"));
2167
3763
  return;
2168
3764
  }
2169
- const targets = [path10.join(cacheDir(), "chrome"), path10.join(cacheDir(), "halaman"), path10.join(logDir(), "hypeframe.log.1")];
2170
- for (const job of fs14.readdirSync(renderDir())) {
3765
+ const targets = [path17.join(cacheDir(), "chrome"), path17.join(cacheDir(), "halaman"), path17.join(logDir(), "hypeframe.log.1")];
3766
+ for (const job of fs21.readdirSync(renderDir())) {
2171
3767
  if (!JOB_ID.test(job))
2172
3768
  continue;
2173
3769
  try {
2174
- const s = JSON.parse(fs14.readFileSync(path10.join(renderDir(), job, "status.json"), "utf8")).status;
3770
+ const s = JSON.parse(fs21.readFileSync(path17.join(renderDir(), job, "status.json"), "utf8")).status;
2175
3771
  if (s === "gagal" || s === "batal" || s === "unggah")
2176
- targets.push(path10.join(renderDir(), job));
3772
+ targets.push(path17.join(renderDir(), job));
2177
3773
  } catch {
2178
- targets.push(path10.join(renderDir(), job));
3774
+ targets.push(path17.join(renderDir(), job));
2179
3775
  }
2180
3776
  }
2181
3777
  let freed = 0;
2182
3778
  for (const p of targets) {
2183
3779
  freed += await sizeOf(p);
2184
- fs14.rmSync(p, { recursive: true, force: true });
3780
+ fs21.rmSync(p, { recursive: true, force: true });
2185
3781
  }
2186
- log.ok(t("clean.done", { size: bytes(freed) }));
3782
+ log.ok(t("clean.done", { size: bytes2(freed) }));
2187
3783
  }
2188
3784
  function report() {
2189
3785
  const s = resolveSettings();
2190
3786
  const a = readAccount();
2191
3787
  let recent = "";
2192
3788
  try {
2193
- recent = fs14.readFileSync(path10.join(logDir(), "hypeframe.log"), "utf8").split(`
3789
+ recent = fs21.readFileSync(path17.join(logDir(), "hypeframe.log"), "utf8").split(`
2194
3790
  `).slice(-400).join(`
2195
3791
  `);
2196
3792
  } catch {
@@ -2199,7 +3795,7 @@ function report() {
2199
3795
  const lines = [
2200
3796
  `hypeframe ${VERSION}`,
2201
3797
  `created ${new Date().toISOString()}`,
2202
- `node ${process.versions.node} · ${process.platform} ${os4.release()} ${process.arch} · ${os4.cpus()[0]?.model ?? "?"} ×${os4.cpus().length} · ${bytes(os4.totalmem())} RAM`,
3798
+ `${runtimeLabel()} · ${process.platform} ${os4.release()} ${process.arch} · ${os4.cpus()[0]?.model ?? "?"} ×${os4.cpus().length} · ${bytes2(os4.totalmem())} RAM`,
2203
3799
  `gateway ${s.gateway}`,
2204
3800
  `web ${s.web}`,
2205
3801
  `gpu ${s.gpu}`,
@@ -2211,25 +3807,26 @@ function report() {
2211
3807
  recent
2212
3808
  ];
2213
3809
  const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
2214
- const file = path10.join(dataDir(), `laporan-${stamp}.txt`);
2215
- fs14.writeFileSync(file, mask(lines.join(`
3810
+ const file = path17.join(dataDir(), `laporan-${stamp}.txt`);
3811
+ fs21.writeFileSync(file, mask(lines.join(`
2216
3812
  `)), { mode: 384 });
2217
3813
  log.ok(t("report.done", { file }));
2218
3814
  log.detail(t("report.hint"));
2219
3815
  return file;
2220
3816
  }
2221
3817
  function update() {
2222
- if (!installedScript()) {
3818
+ if (!launchCommand()) {
2223
3819
  log.info(t("update.npx"));
2224
3820
  log.detail("npx hypeframe@latest");
2225
3821
  return;
2226
3822
  }
2227
3823
  log.info(t("update.running"));
2228
- const r = spawnSync3("npm", ["i", "-g", "hypeframe@latest"], { stdio: "inherit", shell: process.platform === "win32" });
3824
+ const win = process.platform === "win32";
3825
+ const r = isStandalone() ? win ? spawnSync5("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_URL}.ps1 | iex`], { stdio: "inherit" }) : spawnSync5("bash", ["-c", `curl -fsSL ${INSTALL_URL} | bash`], { stdio: "inherit" }) : spawnSync5("npm", ["i", "-g", "hypeframe@latest"], { stdio: "inherit", shell: win });
2229
3826
  if (r.status === 0)
2230
3827
  log.ok(t("update.done"));
2231
3828
  else
2232
- log.error(t("update.failed"));
3829
+ log.error(isStandalone() ? t("update.failedStandalone") : t("update.failed"));
2233
3830
  }
2234
3831
  function openWeb(args) {
2235
3832
  const { web } = resolveSettings(args.flags);
@@ -2239,15 +3836,15 @@ function openWeb(args) {
2239
3836
  log.warn(t("pair.badWeb"));
2240
3837
  }
2241
3838
 
2242
- // packages/hypeframe/src/cli/commands/status.ts
2243
- import fs15 from "node:fs";
2244
- import path11 from "node:path";
3839
+ // src/cli/commands/status.ts
3840
+ import fs22 from "node:fs";
3841
+ import path18 from "node:path";
2245
3842
  function statusRows(args) {
2246
3843
  const s = resolveSettings(args?.flags);
2247
3844
  const a = readAccount();
2248
3845
  const pid = runningPid();
2249
- const chrome = findChrome() || fs15.existsSync(path11.join(cacheDir(), "chrome"));
2250
- const recent = readHistory();
3846
+ const chrome = findChrome() || fs22.existsSync(path18.join(cacheDir(), "chrome"));
3847
+ const recent = readHistory2();
2251
3848
  const k = (key) => color.muted(t(key));
2252
3849
  return [
2253
3850
  [k("status.account"), a && a.gateway === s.gateway ? `${color.ok(icon.ok)} ${maskEmail(a.email)}` : `${color.warn(icon.warn)} ${t("status.notPaired")}`],
@@ -2255,7 +3852,7 @@ function statusRows(args) {
2255
3852
  [k("status.device"), `${s.name} ${color.muted(`(${osName()})`)}`],
2256
3853
  [k("status.render"), `${chrome ? "Chrome" : color.muted(t("status.chromeLater"))} ${color.muted(icon.dot)} ${t("status.gpu")} ${s.gpu ? color.ok(t("status.on")) : color.muted(t("status.off"))}`],
2257
3854
  [k("status.recent"), recent.length ? t("status.recentCount", { n: recent.length }) : color.muted("-")],
2258
- [k("status.version"), `${VERSION} ${color.muted(icon.dot)} Node ${process.versions.node}`]
3855
+ [k("status.version"), `${VERSION} ${color.muted(icon.dot)} ${runtimeLabel()}`]
2259
3856
  ];
2260
3857
  }
2261
3858
  function status(args) {
@@ -2264,8 +3861,8 @@ function status(args) {
2264
3861
  console.log("");
2265
3862
  }
2266
3863
 
2267
- // packages/hypeframe/src/cli/menu.ts
2268
- import * as p2 from "@clack/prompts";
3864
+ // src/cli/menu.ts
3865
+ import * as p3 from "@clack/prompts";
2269
3866
  async function menu(args) {
2270
3867
  process.stdout.write(banner());
2271
3868
  console.log("");
@@ -2275,14 +3872,17 @@ async function menu(args) {
2275
3872
  const s = resolveSettings(args.flags);
2276
3873
  const paired = !!readAccount() && readAccount()?.gateway === s.gateway;
2277
3874
  const running = !!runningPid();
2278
- const choice = await p2.select({
3875
+ const choice = await p3.select({
2279
3876
  message: t("menu.question"),
2280
3877
  options: [
2281
3878
  { value: "start", label: color.brand(t("menu.start")), hint: running ? t("status.running", { pid: runningPid() ?? "" }) : paired ? undefined : t("menu.startPair") },
2282
3879
  { value: "open", label: t("menu.open"), hint: s.web.replace(/^https?:\/\//, "") },
2283
3880
  { value: "bench", label: t("menu.bench") },
2284
3881
  { value: "history", label: t("menu.history") },
2285
- { value: "agent", label: `${color.ai("✦")} ${t("menu.agent")}`, hint: t("menu.soon") },
3882
+ { value: "agent", label: `${color.ai("✦")} ${t("menu.agent")}`, hint: (() => {
3883
+ const n = readInstalled().filter((a) => a.ready).length;
3884
+ return n ? t("menu.agentReady", { n }) : undefined;
3885
+ })() },
2286
3886
  { value: "autostart", label: t("menu.autostart"), hint: autostartEnabled() ? t("status.on") : t("status.off") },
2287
3887
  { value: "config", label: t("menu.config") },
2288
3888
  { value: "doctor", label: t("menu.doctor") },
@@ -2293,15 +3893,15 @@ async function menu(args) {
2293
3893
  { value: "exit", label: color.muted(t("menu.exit")) }
2294
3894
  ]
2295
3895
  });
2296
- if (p2.isCancel(choice) || choice === "exit") {
2297
- p2.outro(color.muted(t("menu.bye")));
3896
+ if (p3.isCancel(choice) || choice === "exit") {
3897
+ p3.outro(color.muted(t("menu.bye")));
2298
3898
  return;
2299
3899
  }
2300
3900
  try {
2301
3901
  switch (choice) {
2302
3902
  case "start":
2303
3903
  if (running) {
2304
- p2.log.warn(t("engine.running"));
3904
+ p3.log.warn(t("engine.running"));
2305
3905
  break;
2306
3906
  }
2307
3907
  await start(args, { fromMenu: true });
@@ -2315,18 +3915,18 @@ async function menu(args) {
2315
3915
  case "history": {
2316
3916
  const items = history();
2317
3917
  if (items.some((i) => i.file)) {
2318
- const go = await p2.confirm({ message: t("history.openFolder"), initialValue: false });
3918
+ const go = await p3.confirm({ message: t("history.openFolder"), initialValue: false });
2319
3919
  if (go === true)
2320
3920
  openFolder(renderDir());
2321
3921
  }
2322
3922
  break;
2323
3923
  }
2324
3924
  case "agent":
2325
- p2.log.message(`${color.ai("✦")} ${t("agent.soon")}`);
3925
+ await agentMenu();
2326
3926
  break;
2327
3927
  case "autostart": {
2328
- const on = await p2.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
2329
- if (!p2.isCancel(on))
3928
+ const on = await p3.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
3929
+ if (!p3.isCancel(on))
2330
3930
  autostart(on ? "on" : "off");
2331
3931
  break;
2332
3932
  }
@@ -2337,7 +3937,7 @@ async function menu(args) {
2337
3937
  await doctor(args);
2338
3938
  break;
2339
3939
  case "clean": {
2340
- const ok = await p2.confirm({ message: t("clean.question"), initialValue: true });
3940
+ const ok = await p3.confirm({ message: t("clean.question"), initialValue: true });
2341
3941
  if (ok === true)
2342
3942
  await clean();
2343
3943
  break;
@@ -2352,19 +3952,19 @@ async function menu(args) {
2352
3952
  await login(args);
2353
3953
  break;
2354
3954
  case "logout": {
2355
- const ok = await p2.confirm({ message: t("confirm.logout"), initialValue: false });
3955
+ const ok = await p3.confirm({ message: t("confirm.logout"), initialValue: false });
2356
3956
  if (ok === true)
2357
3957
  logout();
2358
3958
  break;
2359
3959
  }
2360
3960
  }
2361
3961
  } catch (e) {
2362
- p2.log.error(`${icon.error} ${e.message}`);
3962
+ p3.log.error(`${icon.error} ${e.message}`);
2363
3963
  }
2364
3964
  }
2365
3965
  }
2366
3966
 
2367
- // packages/hypeframe/src/index.ts
3967
+ // src/index.ts
2368
3968
  function help() {
2369
3969
  const rows = [
2370
3970
  ["start", t("help.start")],
@@ -2374,6 +3974,7 @@ function help() {
2374
3974
  ["open", t("help.open")],
2375
3975
  ["doctor", t("help.doctor")],
2376
3976
  ["bench", t("help.bench")],
3977
+ ["agent list|add|login|remove", t("help.agent")],
2377
3978
  ["history", t("help.history")],
2378
3979
  ["autostart on|off", t("help.autostart")],
2379
3980
  ["config", t("help.config")],
@@ -2415,6 +4016,8 @@ var COMMANDS = {
2415
4016
  process.exitCode = checks.some((c) => c.result === "error") ? 1 : 0;
2416
4017
  },
2417
4018
  bench: (a) => bench(a),
4019
+ agent: (a) => agentCommand(a),
4020
+ "mcp-bridge": () => runMcpBridge(),
2418
4021
  history: () => history(),
2419
4022
  autostart: (a) => autostart(a.rest[0]),
2420
4023
  config: (a) => config(a),