hypeframe 0.3.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 +50 -7
  2. package/dist/index.js +1741 -289
  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";
@@ -193,6 +200,33 @@ var id = {
193
200
  "menu.exit": "Keluar",
194
201
  "menu.bye": "Sampai jumpa.",
195
202
  "agent.soon": "Asisten AI yang bekerja langsung di perangkatmu sedang disiapkan.",
203
+ "agent.menuQuestion": "Pilih agen. Pasang dan masuk akun sekali di sini, lalu mengobrol dari HypeFrame Web.",
204
+ "agent.ready": "siap dipakai dari web",
205
+ "agent.needLogin": "perlu masuk akun",
206
+ "agent.notInstalled": "belum dipasang",
207
+ "agent.add": "Pasang dan masuk akun",
208
+ "agent.login": "Masuk akun lagi",
209
+ "agent.remove": "Lepas dari mesin ini",
210
+ "agent.back": "Kembali",
211
+ "agent.installing": "Memasang {name} dari daftar resmi ACP...",
212
+ "agent.installed": "{name} {version} terpasang.",
213
+ "agent.loggingIn": "Masuk akun {name}...",
214
+ "agent.loggedIn": "{name} siap. Buka HypeFrame Web lalu pilih {name} di Asisten (mesin harus menyala).",
215
+ "agent.loginFailed": "{name} belum bisa dipakai: masuk akun belum berhasil. Coba lagi dari menu Asisten AI.",
216
+ "agent.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",
196
230
  "status.account": "Akun",
197
231
  "status.engine": "Mesin",
198
232
  "status.device": "Perangkat",
@@ -268,6 +302,7 @@ var id = {
268
302
  "help.open": "buka HypeFrame Web di browser",
269
303
  "help.doctor": "periksa Node, Chrome, ffmpeg, koneksi, ruang disk",
270
304
  "help.bench": "ukur kecepatan render 720p dan 1080p",
305
+ "help.agent": "pasang dan masuk akun agen AI (Claude Code, Antigravity, Codex, OpenCode)",
271
306
  "help.history": "render 24 jam terakhir",
272
307
  "help.autostart": "nyalakan mesin saat masuk ke komputer",
273
308
  "help.config": "nama perangkat, GPU, bahasa",
@@ -333,6 +368,33 @@ var en = {
333
368
  "menu.exit": "Exit",
334
369
  "menu.bye": "See you.",
335
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",
336
398
  "status.account": "Account",
337
399
  "status.engine": "Engine",
338
400
  "status.device": "Device",
@@ -408,6 +470,7 @@ var en = {
408
470
  "help.open": "open HypeFrame Web in the browser",
409
471
  "help.doctor": "check Node, Chrome, ffmpeg, network, disk space",
410
472
  "help.bench": "measure render speed at 720p and 1080p",
473
+ "help.agent": "install and log in AI agents (Claude Code, Antigravity, Codex, OpenCode)",
411
474
  "help.history": "renders from the last 24 hours",
412
475
  "help.autostart": "start the engine when you sign in",
413
476
  "help.config": "device name, GPU, language",
@@ -425,11 +488,11 @@ function t(key, vars = {}) {
425
488
  return s.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? `{${k}}`));
426
489
  }
427
490
 
428
- // packages/hypeframe/src/ui/log.ts
491
+ // src/ui/log.ts
429
492
  import fs4 from "node:fs";
430
493
  import path2 from "node:path";
431
494
 
432
- // packages/hypeframe/src/ui/theme.ts
495
+ // src/ui/theme.ts
433
496
  import picocolors from "picocolors";
434
497
  var env = process.env;
435
498
  var enabled = !("NO_COLOR" in env) && env.TERM !== "dumb" && ("FORCE_COLOR" in env ? env.FORCE_COLOR !== "0" : !!process.stdout.isTTY);
@@ -463,7 +526,7 @@ var icon = {
463
526
  };
464
527
  var plain = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
465
528
 
466
- // packages/hypeframe/src/ui/log.ts
529
+ // src/ui/log.ts
467
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;
468
531
  var mask = (s) => s.replace(SECRET, (m) => `${m.slice(0, 4)}…`);
469
532
  var MAX_FILE = 1024 * 1024;
@@ -501,12 +564,12 @@ var log = {
501
564
  detail: (m) => write("detail", m)
502
565
  };
503
566
 
504
- // packages/hypeframe/src/cli/commands/start.ts
505
- import crypto4 from "node:crypto";
567
+ // src/cli/commands/start.ts
568
+ import crypto7 from "node:crypto";
506
569
 
507
- // packages/protocol/src/index.ts
570
+ // ../protocol/src/index.ts
508
571
  var PROTOCOL_VERSION = 1;
509
- var ALLOWED_KINDS = ["status", "kunci"];
572
+ var ALLOWED_KINDS = ["status", "kunci", "agen.mulai", "agen.kirim", "agen.izin", "agen.batal", "agen.opsi", "agen.riwayat"];
510
573
  var CloseCode = {
511
574
  BadHello: 4001,
512
575
  Replaced: 4002,
@@ -527,59 +590,15 @@ var EngineError = {
527
590
  BadPackage: "Paket berisi berkas yang tidak diizinkan."
528
591
  };
529
592
 
530
- // packages/hypeframe/src/config/lock.ts
531
- import fs5 from "node:fs";
532
- class AlreadyRunning extends Error {
533
- code = "SUDAH_JALAN";
534
- }
535
- var alive = (pid) => {
536
- try {
537
- process.kill(pid, 0);
538
- return true;
539
- } catch (e) {
540
- return e.code === "EPERM";
541
- }
542
- };
543
- function runningPid() {
544
- try {
545
- const pid = Number(fs5.readFileSync(lockFile(), "utf8"));
546
- return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
547
- } catch {
548
- return null;
549
- }
550
- }
551
- function singleInstance() {
552
- const f = lockFile();
553
- for (let attempt = 0;attempt < 2; attempt++) {
554
- try {
555
- const fd = fs5.openSync(f, "wx");
556
- fs5.writeSync(fd, String(process.pid));
557
- fs5.closeSync(fd);
558
- const release = () => {
559
- try {
560
- if (fs5.readFileSync(f, "utf8") === String(process.pid))
561
- fs5.rmSync(f, { force: true });
562
- } catch {}
563
- process.off("exit", release);
564
- };
565
- process.on("exit", release);
566
- return { release };
567
- } catch (e) {
568
- if (e.code !== "EEXIST")
569
- throw e;
570
- const pid = Number(fs5.readFileSync(f, "utf8"));
571
- if (Number.isInteger(pid) && pid > 0 && alive(pid))
572
- throw new AlreadyRunning("engine already running");
573
- fs5.rmSync(f, { force: true });
574
- }
575
- }
576
- throw new AlreadyRunning("engine already running");
577
- }
578
- // packages/hypeframe/package.json
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
579
598
  var package_default = {
580
599
  name: "hypeframe",
581
- version: "0.3.0",
582
- description: "Local engine for HypeFrame Web: code clips, video renders and (soon) AI agents run on your own machine; the web is just the view.",
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.",
583
602
  keywords: [
584
603
  "hypeframe",
585
604
  "video",
@@ -628,15 +647,1047 @@ var package_default = {
628
647
  }
629
648
  };
630
649
 
631
- // packages/hypeframe/src/config/version.ts
650
+ // src/config/version.ts
632
651
  var VERSION = process.env.HF_MESIN_VERSI || package_default.version;
633
652
 
634
- // packages/hypeframe/src/engine/connection.ts
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";
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";
635
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";
1637
+ class AlreadyRunning extends Error {
1638
+ code = "SUDAH_JALAN";
1639
+ }
1640
+ var alive = (pid) => {
1641
+ try {
1642
+ process.kill(pid, 0);
1643
+ return true;
1644
+ } catch (e) {
1645
+ return e.code === "EPERM";
1646
+ }
1647
+ };
1648
+ function runningPid() {
1649
+ try {
1650
+ const pid = Number(fs11.readFileSync(lockFile(), "utf8"));
1651
+ return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
1652
+ } catch {
1653
+ return null;
1654
+ }
1655
+ }
1656
+ function singleInstance() {
1657
+ const f = lockFile();
1658
+ for (let attempt = 0;attempt < 2; attempt++) {
1659
+ try {
1660
+ const fd = fs11.openSync(f, "wx");
1661
+ fs11.writeSync(fd, String(process.pid));
1662
+ fs11.closeSync(fd);
1663
+ const release = () => {
1664
+ try {
1665
+ if (fs11.readFileSync(f, "utf8") === String(process.pid))
1666
+ fs11.rmSync(f, { force: true });
1667
+ } catch {}
1668
+ process.off("exit", release);
1669
+ };
1670
+ process.on("exit", release);
1671
+ return { release };
1672
+ } catch (e) {
1673
+ if (e.code !== "EEXIST")
1674
+ throw e;
1675
+ const pid = Number(fs11.readFileSync(f, "utf8"));
1676
+ if (Number.isInteger(pid) && pid > 0 && alive(pid))
1677
+ throw new AlreadyRunning("engine already running");
1678
+ fs11.rmSync(f, { force: true });
1679
+ }
1680
+ }
1681
+ throw new AlreadyRunning("engine already running");
1682
+ }
1683
+
1684
+ // src/engine/connection.ts
1685
+ import crypto3 from "node:crypto";
1686
+ import { EventEmitter as EventEmitter2 } from "node:events";
636
1687
  import WebSocket from "ws";
637
1688
  var SILENCE_MAX_MS = 70000;
638
1689
 
639
- class Connection extends EventEmitter {
1690
+ class Connection extends EventEmitter2 {
640
1691
  o;
641
1692
  url;
642
1693
  ws = null;
@@ -672,6 +1723,33 @@ class Connection extends EventEmitter {
672
1723
  news(kind, body = {}) {
673
1724
  this.send({ ...body, t: "kabar", jenis: kind });
674
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
+ }
675
1753
  get connected() {
676
1754
  return this.ws?.readyState === WebSocket.OPEN && !!this.id;
677
1755
  }
@@ -710,6 +1788,8 @@ class Connection extends EventEmitter {
710
1788
  const result = await this.o.handler(m);
711
1789
  if (ws === this.ws)
712
1790
  this.send({ t: "balas", ke: m.dari, id: m.id, ...result });
1791
+ } else if (m.t === "jawab") {
1792
+ this.answer(m);
713
1793
  }
714
1794
  });
715
1795
  ws.on("error", () => {
@@ -720,6 +1800,7 @@ class Connection extends EventEmitter {
720
1800
  if (ws !== this.ws)
721
1801
  return;
722
1802
  this.id = null;
1803
+ this.dropWaiting();
723
1804
  if (code === CloseCode.TokenRevoked) {
724
1805
  deleteAccount();
725
1806
  this.running = false;
@@ -738,21 +1819,22 @@ class Connection extends EventEmitter {
738
1819
  }
739
1820
  }
740
1821
 
741
- // packages/hypeframe/src/engine/handler.ts
1822
+ // src/engine/handler.ts
742
1823
  function createHandler(work) {
743
1824
  return async function handle(c) {
744
1825
  const kind = String(c?.jenis || "");
745
- if (!ALLOWED_KINDS.includes(kind))
1826
+ const fn = ALLOWED_KINDS.includes(kind) ? work[kind] : undefined;
1827
+ if (!fn)
746
1828
  return { ok: false, error: "jenis" };
747
1829
  try {
748
- return { ok: true, ...await work[kind](c) };
1830
+ return { ok: true, ...await fn(c) };
749
1831
  } catch (e) {
750
1832
  return { ok: false, error: "galat", pesan: String(e?.message || e).slice(0, 200) };
751
1833
  }
752
1834
  };
753
1835
  }
754
1836
 
755
- // packages/hypeframe/src/engine/pairing.ts
1837
+ // src/engine/pairing.ts
756
1838
  var sleep = (ms, signal) => new Promise((ok, fail) => {
757
1839
  const timer = setTimeout(ok, ms);
758
1840
  signal?.addEventListener("abort", () => (clearTimeout(timer), fail(new Error("Dibatalkan."))), { once: true });
@@ -828,17 +1910,17 @@ async function pair(o) {
828
1910
  }
829
1911
  }
830
1912
 
831
- // packages/hypeframe/src/render/chrome.ts
1913
+ // src/render/chrome.ts
832
1914
  import { execFileSync } from "node:child_process";
833
- import fs6 from "node:fs";
1915
+ import fs12 from "node:fs";
834
1916
  import http from "node:http";
835
- import path3 from "node:path";
1917
+ import path8 from "node:path";
836
1918
  import { Browser, detectBrowserPlatform, getInstalledBrowsers, install, resolveBuildId } from "@puppeteer/browsers";
837
1919
  import puppeteer from "puppeteer-core";
838
1920
  function candidates() {
839
1921
  const e = process.env;
840
1922
  if (process.platform === "win32") {
841
- 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")]);
842
1924
  }
843
1925
  if (process.platform === "darwin") {
844
1926
  return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
@@ -856,13 +1938,13 @@ function candidates() {
856
1938
  function findChrome() {
857
1939
  const forced = process.env.HYPEFRAME_CHROME;
858
1940
  if (forced)
859
- return fs6.existsSync(forced) ? forced : null;
860
- return candidates().find((p) => fs6.existsSync(p)) || null;
1941
+ return fs12.existsSync(forced) ? forced : null;
1942
+ return candidates().find((p) => fs12.existsSync(p)) || null;
861
1943
  }
862
1944
  async function cachedChrome(cacheDir) {
863
1945
  try {
864
- const all = await getInstalledBrowsers({ cacheDir: path3.join(cacheDir, "chrome") });
865
- return all.find((b) => b.browser === Browser.CHROME && fs6.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;
866
1948
  } catch {
867
1949
  return null;
868
1950
  }
@@ -876,7 +1958,7 @@ async function prepareChrome(cacheDir, progress = () => {
876
1958
  const platform = detectBrowserPlatform();
877
1959
  if (!platform)
878
1960
  throw new Error("Sistem ini belum didukung untuk render (Chrome tidak tersedia).");
879
- const dir = path3.join(cacheDir, "chrome");
1961
+ const dir = path8.join(cacheDir, "chrome");
880
1962
  const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
881
1963
  progress(0, `Chrome ${buildId}`);
882
1964
  const r = await install({
@@ -925,11 +2007,11 @@ async function checkChrome(chrome, { gpu = false } = {}) {
925
2007
  }
926
2008
  }
927
2009
 
928
- // packages/hypeframe/src/render/ffmpeg.ts
929
- import crypto from "node:crypto";
930
- import fs7 from "node:fs";
2010
+ // src/render/ffmpeg.ts
2011
+ import crypto4 from "node:crypto";
2012
+ import fs13 from "node:fs";
931
2013
  import fsp from "node:fs/promises";
932
- import path4 from "node:path";
2014
+ import path9 from "node:path";
933
2015
  import { pipeline } from "node:stream/promises";
934
2016
  import { Readable } from "node:stream";
935
2017
  import zlib from "node:zlib";
@@ -943,19 +2025,19 @@ var FFMPEG_PINNED = {
943
2025
  "darwin-arm64": { sha256: "6be74d6f449889c2e87a75873894f8520cad56c08ac76f2a628d85b0519daaca", size: 19253088 }
944
2026
  };
945
2027
  var exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
946
- var cached2 = (cacheDir) => path4.join(cacheDir, "ffmpeg", FFMPEG_RELEASE, exe);
2028
+ var cached2 = (cacheDir) => path9.join(cacheDir, "ffmpeg", FFMPEG_RELEASE, exe);
947
2029
  async function findFfmpeg(cacheDir) {
948
2030
  const forced = process.env.HYPEFRAME_FFMPEG;
949
2031
  if (forced)
950
- return fs7.existsSync(forced) ? forced : null;
2032
+ return fs13.existsSync(forced) ? forced : null;
951
2033
  try {
952
2034
  const mod = await import("ffmpeg-static");
953
2035
  const p = typeof mod.default === "string" ? mod.default : null;
954
- if (p && fs7.existsSync(p))
2036
+ if (p && fs13.existsSync(p))
955
2037
  return p;
956
2038
  } catch {}
957
2039
  const c = cached2(cacheDir);
958
- return fs7.existsSync(c) ? c : null;
2040
+ return fs13.existsSync(c) ? c : null;
959
2041
  }
960
2042
  async function downloadVerified(url, sha256, dest, progress = () => {
961
2043
  return;
@@ -964,9 +2046,9 @@ async function downloadVerified(url, sha256, dest, progress = () => {
964
2046
  if (!r.ok || !r.body)
965
2047
  throw new Error(`download ${r.status}`);
966
2048
  const total = Number(r.headers.get("content-length")) || 0;
967
- await fsp.mkdir(path4.dirname(dest), { recursive: true });
2049
+ await fsp.mkdir(path9.dirname(dest), { recursive: true });
968
2050
  const tmp = `${dest}.download`;
969
- const hash = crypto.createHash("sha256");
2051
+ const hash = crypto4.createHash("sha256");
970
2052
  let got = 0;
971
2053
  let last = -10;
972
2054
  const body = Readable.fromWeb(r.body).on("data", (c) => {
@@ -976,13 +2058,13 @@ async function downloadVerified(url, sha256, dest, progress = () => {
976
2058
  if (pct - last >= 10)
977
2059
  last = pct, progress(pct);
978
2060
  });
979
- await pipeline(body, fs7.createWriteStream(tmp));
2061
+ await pipeline(body, fs13.createWriteStream(tmp));
980
2062
  if (hash.digest("hex") !== sha256) {
981
2063
  await fsp.rm(tmp, { force: true });
982
2064
  throw new Error("ffmpeg: sidik unduhan tidak cocok, berkas ditolak.");
983
2065
  }
984
2066
  if (gunzip) {
985
- await pipeline(fs7.createReadStream(tmp), zlib.createGunzip(), fs7.createWriteStream(`${tmp}.raw`));
2067
+ await pipeline(fs13.createReadStream(tmp), zlib.createGunzip(), fs13.createWriteStream(`${tmp}.raw`));
986
2068
  await fsp.rm(tmp, { force: true });
987
2069
  await fsp.rename(`${tmp}.raw`, dest);
988
2070
  } else
@@ -1005,17 +2087,17 @@ async function prepareFfmpeg(cacheDir, progress = () => {
1005
2087
  return cached2(cacheDir);
1006
2088
  }
1007
2089
 
1008
- // packages/hypeframe/src/render/job.ts
1009
- import { spawn } from "node:child_process";
1010
- import crypto2 from "node:crypto";
1011
- import fs8 from "node:fs";
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";
1012
2094
  import fsp2 from "node:fs/promises";
1013
- import path5 from "node:path";
2095
+ import path10 from "node:path";
1014
2096
  import puppeteer2 from "puppeteer-core";
1015
2097
  var LIMIT_SECONDS = 1800;
1016
2098
  function run(cmd, args, limitSeconds = 600) {
1017
2099
  return new Promise((ok, fail) => {
1018
- const p = spawn(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
2100
+ const p = spawn2(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
1019
2101
  let err = "";
1020
2102
  p.stderr.on("data", (d) => err = (err + d).slice(-2000));
1021
2103
  const timer = setTimeout(() => p.kill("SIGKILL"), limitSeconds * 1000);
@@ -1027,7 +2109,7 @@ function run(cmd, args, limitSeconds = 600) {
1027
2109
  function saveBody(req, to, max) {
1028
2110
  return new Promise((ok, fail) => {
1029
2111
  let n = 0;
1030
- const out = fs8.createWriteStream(to);
2112
+ const out = fs14.createWriteStream(to);
1031
2113
  req.on("data", (d) => {
1032
2114
  n += d.length;
1033
2115
  if (n > max)
@@ -1058,7 +2140,7 @@ function createJobRunner(o) {
1058
2140
  const renderer = async (task, { progress, signal }) => {
1059
2141
  if (task.kind === "klip" && task.transparent && !transparent)
1060
2142
  throw new Error(EngineError.NoTransparent);
1061
- const key = crypto2.randomBytes(16).toString("hex");
2143
+ const key = crypto5.randomBytes(16).toString("hex");
1062
2144
  let finish;
1063
2145
  const finished = new Promise((ok) => finish = ok);
1064
2146
  running.set(task.job, { key, task, progress, finish });
@@ -1069,9 +2151,9 @@ function createJobRunner(o) {
1069
2151
  let browser;
1070
2152
  try {
1071
2153
  progress(0, "Menyiapkan");
1072
- const profile = path5.join(task.dir, "profil");
1073
- await fsp2.mkdir(path5.join(profile, "Default"), { recursive: true });
1074
- await fsp2.writeFile(path5.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" } } } } }));
1075
2157
  browser = await puppeteer2.launch({
1076
2158
  executablePath: chrome,
1077
2159
  headless: true,
@@ -1101,9 +2183,9 @@ function createJobRunner(o) {
1101
2183
  if (result.error)
1102
2184
  throw new Error(result.error);
1103
2185
  progress(99, clip ? "Menyelesaikan klip" : "Menyelesaikan video");
1104
- const raw = path5.join(task.dir, "mentah.mp4");
2186
+ const raw = path10.join(task.dir, "mentah.mp4");
1105
2187
  const webm = clip && task.transparent;
1106
- const file = path5.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
2188
+ const file = path10.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
1107
2189
  if (clip)
1108
2190
  await fsp2.rename(raw, file);
1109
2191
  else
@@ -1130,11 +2212,11 @@ function createJobRunner(o) {
1130
2212
  return res.writeHead(403), res.end(), true;
1131
2213
  const pkg = r.task.packageDir;
1132
2214
  if (m[2] === "proyek.json" || m[2] === "klip.json" || m[3]) {
1133
- const f = m[3] ? path5.join(pkg, "aset", m[3]) : path5.join(pkg, m[2]);
1134
- 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))
1135
2217
  return res.writeHead(404), res.end(), true;
1136
2218
  res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp2.stat(f)).size });
1137
- fs8.createReadStream(f).pipe(res);
2219
+ fs14.createReadStream(f).pipe(res);
1138
2220
  return true;
1139
2221
  }
1140
2222
  if (m[2] === "kemajuan") {
@@ -1151,7 +2233,7 @@ function createJobRunner(o) {
1151
2233
  r.finish({ error: String(b.pesan || "Render gagal.").slice(0, 300) });
1152
2234
  return res.writeHead(204), res.end(), true;
1153
2235
  }
1154
- await saveBody(req, path5.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
2236
+ await saveBody(req, path10.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
1155
2237
  r.finish({ audio: String(req.headers["x-kodek-audio"] || "") });
1156
2238
  res.writeHead(204);
1157
2239
  res.end();
@@ -1160,10 +2242,10 @@ function createJobRunner(o) {
1160
2242
  return { renderer, route, setPort: (p) => void (port = p) };
1161
2243
  }
1162
2244
 
1163
- // packages/hypeframe/src/render/page.ts
1164
- import fs9 from "node:fs";
2245
+ // src/render/page.ts
2246
+ import fs15 from "node:fs";
1165
2247
  import fsp3 from "node:fs/promises";
1166
- import path6 from "node:path";
2248
+ import path11 from "node:path";
1167
2249
  var TYPES = {
1168
2250
  ".html": "text/html; charset=utf-8",
1169
2251
  ".js": "text/javascript",
@@ -1184,13 +2266,13 @@ var SAFE_PATH = /^[\w@.+-]+(?:\/[\w@.+-]+)*$/;
1184
2266
  var VERSION_ID = /^[0-9a-f]{12}$/;
1185
2267
  function createPage({ web, cacheDir }) {
1186
2268
  const base = `${String(web || "").replace(/\/+$/, "")}/render/`;
1187
- const root = path6.join(cacheDir, "halaman");
2269
+ const root = path11.join(cacheDir, "halaman");
1188
2270
  let version = null;
1189
- const versionDir = () => path6.join(root, version);
2271
+ const versionDir = () => path11.join(root, version);
1190
2272
  const pending = new Map;
1191
2273
  async function download(rel) {
1192
- const target = path6.join(versionDir(), rel);
1193
- if (fs9.existsSync(target))
2274
+ const target = path11.join(versionDir(), rel);
2275
+ if (fs15.existsSync(target))
1194
2276
  return target;
1195
2277
  if (!pending.has(rel)) {
1196
2278
  pending.set(rel, (async () => {
@@ -1198,7 +2280,7 @@ function createPage({ web, cacheDir }) {
1198
2280
  if (!r.ok)
1199
2281
  throw Object.assign(new Error(`halaman ${rel}: ${r.status}`), { status: r.status });
1200
2282
  const body = Buffer.from(await r.arrayBuffer());
1201
- await fsp3.mkdir(path6.dirname(target), { recursive: true });
2283
+ await fsp3.mkdir(path11.dirname(target), { recursive: true });
1202
2284
  await fsp3.writeFile(`${target}.tmp`, body);
1203
2285
  await fsp3.rename(`${target}.tmp`, target);
1204
2286
  return target;
@@ -1222,10 +2304,10 @@ function createPage({ web, cacheDir }) {
1222
2304
  await download(f);
1223
2305
  if (old !== version) {
1224
2306
  const all = (await fsp3.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
1225
- const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(path6.join(root, d))).mtimeMs })));
2307
+ const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(path11.join(root, d))).mtimeMs })));
1226
2308
  for (const { d } of dated.sort((a, b) => b.t - a.t).slice(2))
1227
2309
  if (d !== version)
1228
- await fsp3.rm(path6.join(root, d), { recursive: true, force: true });
2310
+ await fsp3.rm(path11.join(root, d), { recursive: true, force: true });
1229
2311
  }
1230
2312
  return { version };
1231
2313
  }
@@ -1242,8 +2324,8 @@ function createPage({ web, cacheDir }) {
1242
2324
  return res.writeHead(404), res.end(), true;
1243
2325
  try {
1244
2326
  const f = await download(rel);
1245
- res.writeHead(200, { "content-type": TYPES[path6.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
1246
- 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);
1247
2329
  } catch (e) {
1248
2330
  res.writeHead(e.status === 404 ? 404 : 502);
1249
2331
  res.end();
@@ -1259,15 +2341,15 @@ function createPage({ web, cacheDir }) {
1259
2341
  };
1260
2342
  }
1261
2343
 
1262
- // packages/hypeframe/src/render/service.ts
1263
- import crypto3 from "node:crypto";
1264
- import fs10 from "node:fs";
2344
+ // src/render/service.ts
2345
+ import crypto6 from "node:crypto";
2346
+ import fs16 from "node:fs";
1265
2347
  import fsp4 from "node:fs/promises";
1266
2348
  import http2 from "node:http";
1267
- import path7 from "node:path";
2349
+ import path12 from "node:path";
1268
2350
  import yauzl from "yauzl";
1269
2351
  var ACTIVE = new Set(["unggah", "antre", "jalan"]);
1270
- var safeEqual = (a, b) => a.length === b.length && crypto3.timingSafeEqual(Buffer.from(a), Buffer.from(b));
2352
+ var safeEqual = (a, b) => a.length === b.length && crypto6.timingSafeEqual(Buffer.from(a), Buffer.from(b));
1271
2353
  var BAD_ENTRY = /relative path|absolute path|invalid characters/i;
1272
2354
  function listZip(f) {
1273
2355
  return new Promise((ok, fail) => {
@@ -1291,14 +2373,14 @@ function extractZip(f, to) {
1291
2373
  zip.on("entry", (en) => {
1292
2374
  if (en.fileName.endsWith("/"))
1293
2375
  return zip.readEntry();
1294
- const target = path7.join(to, en.fileName);
1295
- if (!target.startsWith(to + path7.sep))
2376
+ const target = path12.join(to, en.fileName);
2377
+ if (!target.startsWith(to + path12.sep))
1296
2378
  return fail(new Error(EngineError.BadPackage));
1297
- fs10.mkdirSync(path7.dirname(target), { recursive: true });
2379
+ fs16.mkdirSync(path12.dirname(target), { recursive: true });
1298
2380
  zip.openReadStream(en, (e2, s) => {
1299
2381
  if (e2 || !s)
1300
2382
  return fail(e2 ?? new Error("zip"));
1301
- const out = fs10.createWriteStream(target);
2383
+ const out = fs16.createWriteStream(target);
1302
2384
  s.pipe(out);
1303
2385
  out.on("finish", () => zip.readEntry());
1304
2386
  out.on("error", fail);
@@ -1313,13 +2395,13 @@ function extractZip(f, to) {
1313
2395
  function saveBody2(req, to, max) {
1314
2396
  return new Promise((ok, fail) => {
1315
2397
  let n = 0;
1316
- const out = fs10.createWriteStream(to);
2398
+ const out = fs16.createWriteStream(to);
1317
2399
  req.on("data", (d) => {
1318
2400
  n += d.length;
1319
2401
  if (n > max) {
1320
2402
  req.destroy();
1321
2403
  out.destroy();
1322
- fs10.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
2404
+ fs16.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
1323
2405
  }
1324
2406
  });
1325
2407
  req.pipe(out);
@@ -1347,8 +2429,8 @@ async function createRenderService(o) {
1347
2429
  return;
1348
2430
  } } = o;
1349
2431
  const origins = new Set([].concat(o.origin || []));
1350
- const sign = (kind, body) => crypto3.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
1351
- const dir = (job) => path7.join(folder, job);
2432
+ const sign = (kind, body) => crypto6.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
2433
+ const dir = (job) => path12.join(folder, job);
1352
2434
  await fsp4.mkdir(folder, { recursive: true });
1353
2435
  function readTicket(req) {
1354
2436
  const tk = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
@@ -1370,7 +2452,7 @@ async function createRenderService(o) {
1370
2452
  const jobs = new Map;
1371
2453
  const queue = [];
1372
2454
  let current = null;
1373
- const persist = (t) => fsp4.writeFile(path7.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(() => {
1374
2456
  return;
1375
2457
  });
1376
2458
  const update = (t, patch) => (Object.assign(t, patch, { diperbarui: Date.now() }), void persist(t));
@@ -1389,19 +2471,19 @@ async function createRenderService(o) {
1389
2471
  });
1390
2472
  async function clearFiles(t, all = false) {
1391
2473
  for (const n of all ? ["."] : ["paket", "paket.zip", "profil", "mentah.mp4", "mentah.webm"])
1392
- await fsp4.rm(path7.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(() => {
1393
2475
  return;
1394
2476
  });
1395
2477
  if (!all) {
1396
2478
  for (const f of await fsp4.readdir(dir(t.job)).catch(() => []))
1397
2479
  if (/^p\d+$/.test(f))
1398
- await fsp4.rm(path7.join(dir(t.job), f), { force: true });
2480
+ await fsp4.rm(path12.join(dir(t.job), f), { force: true });
1399
2481
  }
1400
2482
  }
1401
2483
  async function openPackage(t) {
1402
2484
  const d = dir(t.job);
1403
2485
  const main = t.tiket.jenis === "klip" ? "klip.json" : "proyek.json";
1404
- const entries = await listZip(path7.join(d, "paket.zip"));
2486
+ const entries = await listZip(path12.join(d, "paket.zip"));
1405
2487
  const names = entries.map((x) => x.name).filter((n) => !n.endsWith("/"));
1406
2488
  if (names.some((n) => n.startsWith("/") || n.includes("..") || n.includes("\\") || n !== main && !/^aset\/[\w-]+$/.test(n)))
1407
2489
  throw new Error(EngineError.BadPackage);
@@ -1409,10 +2491,10 @@ async function createRenderService(o) {
1409
2491
  throw new Error(`Paket tidak berisi ${main}.`);
1410
2492
  if (entries.reduce((a, x) => a + x.size, 0) > maxUnzippedMb * 1048576)
1411
2493
  throw new Error("Isi paket terlalu besar.");
1412
- await extractZip(path7.join(d, "paket.zip"), path7.join(d, "paket"));
1413
- await fsp4.rm(path7.join(d, "paket.zip"), { force: true });
1414
- const j = JSON.parse(await fsp4.readFile(path7.join(d, "paket", main), "utf8"));
1415
- const has = (id) => /^[\w-]+$/.test(id) && fs10.existsSync(path7.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));
1416
2498
  if (main === "klip.json") {
1417
2499
  const k = j.klip || {};
1418
2500
  const seconds = Number(k.durationInFrames) / Number(k.fps);
@@ -1460,7 +2542,7 @@ async function createRenderService(o) {
1460
2542
  job: t.job,
1461
2543
  kind: t.tiket.jenis,
1462
2544
  dir: dir(t.job),
1463
- packageDir: path7.join(dir(t.job), "paket"),
2545
+ packageDir: path12.join(dir(t.job), "paket"),
1464
2546
  transparent: !!t.transparan,
1465
2547
  persen: t.persen,
1466
2548
  width: t.tiket.w,
@@ -1480,7 +2562,7 @@ async function createRenderService(o) {
1480
2562
  const size = (await fsp4.stat(h.file)).size;
1481
2563
  if (size < 200)
1482
2564
  throw new Error(EngineError.EmptyResult);
1483
- update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path7.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 });
1484
2566
  onJob("done", t);
1485
2567
  } catch (e) {
1486
2568
  if (t.status !== "batal") {
@@ -1518,10 +2600,10 @@ async function createRenderService(o) {
1518
2600
  if (a > z)
1519
2601
  return res.writeHead(416, { ...h, "content-range": `bytes */${st.size}` }), res.end();
1520
2602
  res.writeHead(206, { ...h, "content-length": z - a + 1, "content-range": `bytes ${a}-${z}/${st.size}` });
1521
- return void fs10.createReadStream(f, { start: a, end: z }).pipe(res);
2603
+ return void fs16.createReadStream(f, { start: a, end: z }).pipe(res);
1522
2604
  }
1523
2605
  res.writeHead(200, { ...h, "content-length": st.size });
1524
- fs10.createReadStream(f).pipe(res);
2606
+ fs16.createReadStream(f).pipe(res);
1525
2607
  }
1526
2608
  const ROUTE = /^\/tugas(?:\/(r_[a-f0-9]{16})(\/potongan\/(\d{1,4})|\/mulai|\/hasil)?)?$/;
1527
2609
  const server = http2.createServer(async (req, res) => {
@@ -1560,13 +2642,13 @@ async function createRenderService(o) {
1560
2642
  if (t.status !== "unggah")
1561
2643
  return json(req, res, 409, { galat: "Unggahan sudah ditutup." });
1562
2644
  const n = Number(m[3]);
1563
- const f = path7.join(dir(job), `p${n}`);
1564
- const before = fs10.existsSync(f) ? (await fsp4.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;
1565
2647
  const room = Number(ticket.maksMb) * 1048576 - (t.terunggah - before);
1566
2648
  const size = await saveBody2(req, f, Math.min(partMb * 1048576 + 1024, room));
1567
2649
  const expected = String(req.headers["x-sha256"] || "").toLowerCase();
1568
2650
  if (expected) {
1569
- const digest = crypto3.createHash("sha256").update(await fsp4.readFile(f)).digest("hex");
2651
+ const digest = crypto6.createHash("sha256").update(await fsp4.readFile(f)).digest("hex");
1570
2652
  if (digest !== expected) {
1571
2653
  await fsp4.rm(f, { force: true });
1572
2654
  update(t, { terunggah: t.terunggah - before });
@@ -1583,13 +2665,13 @@ async function createRenderService(o) {
1583
2665
  const count = Number(b.jumlah);
1584
2666
  if (!(count > 0 && count < 1e4))
1585
2667
  return json(req, res, 400, { galat: "Jumlah potongan tidak valid." });
1586
- const zip = path7.join(dir(job), "paket.zip");
1587
- const out = fs10.createWriteStream(zip);
1588
- const hash = crypto3.createHash("sha256");
2668
+ const zip = path12.join(dir(job), "paket.zip");
2669
+ const out = fs16.createWriteStream(zip);
2670
+ const hash = crypto6.createHash("sha256");
1589
2671
  let total = 0;
1590
2672
  for (let i = 0;i < count; i++) {
1591
- const f = path7.join(dir(job), `p${i}`);
1592
- if (!fs10.existsSync(f))
2673
+ const f = path12.join(dir(job), `p${i}`);
2674
+ if (!fs16.existsSync(f))
1593
2675
  return out.destroy(), json(req, res, 400, { galat: `Potongan ${i + 1} belum terunggah.` });
1594
2676
  const part = await fsp4.readFile(f);
1595
2677
  hash.update(part);
@@ -1619,8 +2701,8 @@ async function createRenderService(o) {
1619
2701
  return json(req, res, 200, summary(t));
1620
2702
  }
1621
2703
  if (m[2] === "/hasil" && (req.method === "GET" || req.method === "HEAD")) {
1622
- const f = t.hasilBerkas ? path7.join(dir(job), t.hasilBerkas) : "";
1623
- 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))
1624
2706
  return json(req, res, 409, { galat: "Video belum jadi." });
1625
2707
  const webm = t.hasilJenis === "video/webm";
1626
2708
  return sendFile(req, res, f, webm ? "video/webm" : "video/mp4", `hypeframe-${job}.${webm ? "webm" : "mp4"}`);
@@ -1651,7 +2733,7 @@ async function createRenderService(o) {
1651
2733
  if (!JOB_ID.test(job))
1652
2734
  continue;
1653
2735
  try {
1654
- const t = JSON.parse(await fsp4.readFile(path7.join(dir(job), "status.json"), "utf8"));
2736
+ const t = JSON.parse(await fsp4.readFile(path12.join(dir(job), "status.json"), "utf8"));
1655
2737
  if (t.status === "jalan" || t.status === "antre")
1656
2738
  update(t, { status: "gagal", galat: EngineError.Restarted });
1657
2739
  jobs.set(job, t);
@@ -1685,7 +2767,7 @@ async function createRenderService(o) {
1685
2767
  };
1686
2768
  }
1687
2769
 
1688
- // packages/hypeframe/src/ui/banner.ts
2770
+ // src/ui/banner.ts
1689
2771
  function banner() {
1690
2772
  const mark = color.brand("◆");
1691
2773
  return `
@@ -1694,8 +2776,8 @@ function banner() {
1694
2776
  `;
1695
2777
  }
1696
2778
 
1697
- // packages/hypeframe/src/util/format.ts
1698
- function bytes(n) {
2779
+ // src/util/format.ts
2780
+ function bytes2(n) {
1699
2781
  if (!(n > 0))
1700
2782
  return "0 B";
1701
2783
  const units = ["B", "KB", "MB", "GB", "TB"];
@@ -1731,13 +2813,13 @@ function table(rows, indent = " ") {
1731
2813
  `);
1732
2814
  }
1733
2815
 
1734
- // packages/hypeframe/src/util/open.ts
1735
- import { spawn as spawn2 } from "node:child_process";
2816
+ // src/util/open.ts
2817
+ import { spawn as spawn3 } from "node:child_process";
1736
2818
  var PAIRING_LINK = new RegExp(`^https?://[A-Za-z0-9.-]+(:\\d+)?/sambung\\?kode=${PAIRING_CODE.source.slice(1, -1)}$`);
1737
2819
  var WEB_ORIGIN = /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?\/?$/;
1738
2820
  function launch(target) {
1739
2821
  const [cmd, args] = process.platform === "win32" ? ["explorer.exe", [target]] : [process.platform === "darwin" ? "open" : "xdg-open", [target]];
1740
- const p = spawn2(cmd, args, { stdio: "ignore", detached: true });
2822
+ const p = spawn3(cmd, args, { stdio: "ignore", detached: true });
1741
2823
  p.on("error", () => {
1742
2824
  return;
1743
2825
  });
@@ -1753,7 +2835,7 @@ function openFolder(dir) {
1753
2835
  launch(dir);
1754
2836
  }
1755
2837
 
1756
- // packages/hypeframe/src/cli/commands/start.ts
2838
+ // src/cli/commands/start.ts
1757
2839
  async function pairDevice(s, noBrowser = false) {
1758
2840
  const a = await pair({
1759
2841
  gateway: s.gateway,
@@ -1797,8 +2879,16 @@ async function start(args, { fromMenu = false } = {}) {
1797
2879
  account = await pairDevice(s, args.flags.noBrowser);
1798
2880
  else
1799
2881
  log.ok(t("pair.done", { email: color.bold(maskEmail(account.email)) }));
1800
- const capabilities = { render: false, chrome: null, transparan: false };
1801
- const key = crypto4.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");
1802
2892
  const cache = cacheDir();
1803
2893
  const page = createPage({ web: s.web, cacheDir: cache });
1804
2894
  let runner = null;
@@ -1808,13 +2898,13 @@ async function start(args, { fromMenu = false } = {}) {
1808
2898
  key,
1809
2899
  origin: new URL(s.web).origin,
1810
2900
  renderer: (task, o) => runner ? runner.renderer(task, o) : Promise.reject(new Error(EngineError.NotReady)),
1811
- extraRoute: (req, res, url) => runner ? runner.route(req, res, url) : page.route(req, res, url),
2901
+ extraRoute: async (req, res, url) => await agents.route(req, res, url) || (runner ? runner.route(req, res, url) : page.route(req, res, url)),
1812
2902
  onJob: (event, j) => {
1813
2903
  if (event === "started") {
1814
2904
  started.set(j.job, Date.now());
1815
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`) }));
1816
2906
  } else if (event === "done") {
1817
- 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) }));
1818
2908
  started.delete(j.job);
1819
2909
  } else if (event === "failed") {
1820
2910
  log.warn(t("render.jobFailed", { reason: j.galat || "?" }));
@@ -1825,17 +2915,28 @@ async function start(args, { fromMenu = false } = {}) {
1825
2915
  }
1826
2916
  }
1827
2917
  });
2918
+ servicePort = service.port;
1828
2919
  const handler = createHandler({
1829
2920
  status: () => ({ versi: VERSION, os: osName(), kemampuan: capabilities }),
1830
2921
  kunci: () => {
1831
2922
  if (!capabilities.render)
1832
2923
  throw new Error(EngineError.NotReady);
1833
2924
  return { port: service.port, kunci: key, versi: VERSION };
1834
- }
2925
+ },
2926
+ ...agents.work
1835
2927
  });
1836
- 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();
1837
2938
  let connectedBefore = false;
1838
- conn.on("connected", () => {
2939
+ engineConn.on("connected", () => {
1839
2940
  if (connectedBefore)
1840
2941
  log.ok(t("engine.reconnected"));
1841
2942
  else {
@@ -1844,16 +2945,16 @@ async function start(args, { fromMenu = false } = {}) {
1844
2945
  }
1845
2946
  connectedBefore = true;
1846
2947
  });
1847
- conn.on("disconnected", () => log.warn(t("engine.lost")));
1848
- conn.on("revoked", () => {
2948
+ engineConn.on("disconnected", () => log.warn(t("engine.lost")));
2949
+ engineConn.on("revoked", () => {
1849
2950
  log.warn(t("engine.revoked"));
1850
2951
  process.exit(0);
1851
2952
  });
1852
- conn.on("stopped", (reason) => {
2953
+ engineConn.on("stopped", (reason) => {
1853
2954
  log.error(reason === "protocol" ? t("engine.tooOld") : t("engine.replaced"));
1854
2955
  process.exit(1);
1855
2956
  });
1856
- conn.start();
2957
+ engineConn.start();
1857
2958
  let lastPercent = -10;
1858
2959
  const chromeProgress = (percent, what) => {
1859
2960
  if (percent === 0)
@@ -1880,8 +2981,8 @@ async function start(args, { fromMenu = false } = {}) {
1880
2981
  runner = createJobRunner({ chrome, ffmpeg, page, gpu: s.gpu, transparent: info.transparent, note: (m) => log.detail(m) });
1881
2982
  runner.setPort(service.port);
1882
2983
  Object.assign(capabilities, { render: true, chrome: info.version, transparan: info.transparent });
1883
- conn.setInfo({ kemampuan: capabilities });
1884
- conn.news("status", { kemampuan: capabilities });
2984
+ engineConn.setInfo({ kemampuan: capabilities });
2985
+ engineConn.news("status", { kemampuan: capabilities });
1885
2986
  log.ok(t("render.ready", { chrome: info.version, extra: info.transparent ? "" : t("render.noAlpha") }));
1886
2987
  } catch (e) {
1887
2988
  log.warn(t("render.notYet", { reason: e.message }));
@@ -1895,8 +2996,8 @@ async function start(args, { fromMenu = false } = {}) {
1895
2996
  const stop = () => {
1896
2997
  console.log("");
1897
2998
  log.info(t("engine.stopped"));
1898
- conn.stop();
1899
- service.stop().finally(() => process.exit(0));
2999
+ engineConn.stop();
3000
+ Promise.all([service.stop(), agents.stop()]).finally(() => process.exit(0));
1900
3001
  setTimeout(() => process.exit(0), 2000).unref();
1901
3002
  };
1902
3003
  process.once("SIGINT", stop);
@@ -1906,7 +3007,7 @@ async function start(args, { fromMenu = false } = {}) {
1906
3007
  });
1907
3008
  }
1908
3009
 
1909
- // packages/hypeframe/src/cli/commands/account.ts
3010
+ // src/cli/commands/account.ts
1910
3011
  async function login(args) {
1911
3012
  const s = resolveSettings(args.flags);
1912
3013
  const a = readAccount();
@@ -1922,49 +3023,25 @@ function logout() {
1922
3023
  log.ok(t("logout.done"));
1923
3024
  }
1924
3025
 
1925
- // packages/hypeframe/src/cli/commands/autostart.ts
1926
- import { spawnSync } from "node:child_process";
1927
- import fs12 from "node:fs";
3026
+ // src/cli/commands/autostart.ts
3027
+ import { spawnSync as spawnSync2 } from "node:child_process";
3028
+ import fs17 from "node:fs";
1928
3029
  import os3 from "node:os";
1929
- import path9 from "node:path";
1930
-
1931
- // packages/hypeframe/src/util/runtime.ts
1932
- import fs11 from "node:fs";
1933
- import path8 from "node:path";
1934
- function isStandalone() {
1935
- return path8.basename(process.execPath).toLowerCase().startsWith("hypeframe");
1936
- }
1937
- function runtimeLabel() {
1938
- const bun = process.versions.bun;
1939
- return bun && !isStandalone() ? `Bun ${bun}` : isStandalone() ? `Bun ${bun ?? "?"} (standalone)` : `Node ${process.versions.node}`;
1940
- }
1941
- function launchCommand() {
1942
- if (isStandalone())
1943
- return [process.execPath];
1944
- try {
1945
- const script = fs11.realpathSync(process.argv[1] || "");
1946
- return /[\\/]_npx[\\/]/.test(script) ? null : [process.execPath, script];
1947
- } catch {
1948
- return null;
1949
- }
1950
- }
1951
- var INSTALL_URL = "https://hype-frame.com/install";
1952
-
1953
- // packages/hypeframe/src/cli/commands/autostart.ts
3030
+ import path13 from "node:path";
1954
3031
  function entryFile() {
1955
3032
  const home = os3.homedir();
1956
3033
  if (process.platform === "win32")
1957
- return path9.join(process.env.APPDATA || path9.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");
1958
3035
  if (process.platform === "darwin")
1959
- return path9.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
3036
+ return path13.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
1960
3037
  if (hasSystemd())
1961
- return path9.join(home, ".config", "systemd", "user", "hypeframe.service");
1962
- return path9.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");
1963
3040
  }
1964
3041
  function hasSystemd() {
1965
- 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;
1966
3043
  }
1967
- var autostartEnabled = () => fs12.existsSync(entryFile());
3044
+ var autostartEnabled = () => fs17.existsSync(entryFile());
1968
3045
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1969
3046
  function autostart(mode) {
1970
3047
  const file = entryFile();
@@ -1975,8 +3052,8 @@ function autostart(mode) {
1975
3052
  }
1976
3053
  if (mode === "off") {
1977
3054
  if (process.platform === "linux" && file.endsWith(".service"))
1978
- spawnSync("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
1979
- fs12.rmSync(file, { force: true });
3055
+ spawnSync2("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
3056
+ fs17.rmSync(file, { force: true });
1980
3057
  log.ok(t("autostart.off"));
1981
3058
  return;
1982
3059
  }
@@ -1991,14 +3068,14 @@ function autostart(mode) {
1991
3068
  return;
1992
3069
  }
1993
3070
  const quoted = cmd.map((c) => `"${c}"`).join(" ");
1994
- fs12.mkdirSync(path9.dirname(file), { recursive: true });
3071
+ fs17.mkdirSync(path13.dirname(file), { recursive: true });
1995
3072
  if (process.platform === "win32") {
1996
- fs12.writeFileSync(file, `@echo off\r
3073
+ fs17.writeFileSync(file, `@echo off\r
1997
3074
  start "HypeFrame" /min ${quoted} start --no-browser\r
1998
3075
  `);
1999
3076
  } else if (process.platform === "darwin") {
2000
- const out = path9.join(logDir(), "autostart.log");
2001
- fs12.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"?>
2002
3079
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2003
3080
  <plist version="1.0"><dict>
2004
3081
  <key>Label</key><string>com.hypeframe.engine</string>
@@ -2009,7 +3086,7 @@ start "HypeFrame" /min ${quoted} start --no-browser\r
2009
3086
  </dict></plist>
2010
3087
  `);
2011
3088
  } else if (file.endsWith(".service")) {
2012
- fs12.writeFileSync(file, `[Unit]
3089
+ fs17.writeFileSync(file, `[Unit]
2013
3090
  Description=HypeFrame engine
2014
3091
  After=network-online.target
2015
3092
 
@@ -2021,10 +3098,10 @@ RestartSec=60
2021
3098
  [Install]
2022
3099
  WantedBy=default.target
2023
3100
  `);
2024
- spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
2025
- 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" });
2026
3103
  } else {
2027
- fs12.writeFileSync(file, `[Desktop Entry]
3104
+ fs17.writeFileSync(file, `[Desktop Entry]
2028
3105
  Type=Application
2029
3106
  Name=HypeFrame engine
2030
3107
  Exec=${quoted} start --no-browser
@@ -2036,7 +3113,7 @@ X-GNOME-Autostart-enabled=true
2036
3113
  log.detail(file);
2037
3114
  }
2038
3115
 
2039
- // packages/hypeframe/src/cli/commands/bench.ts
3116
+ // src/cli/commands/bench.ts
2040
3117
  import http3 from "node:http";
2041
3118
  import puppeteer3 from "puppeteer-core";
2042
3119
  var FRAMES = 150;
@@ -2122,8 +3199,377 @@ async function bench(args) {
2122
3199
  `);
2123
3200
  }
2124
3201
 
2125
- // packages/hypeframe/src/cli/commands/config.ts
3202
+ // src/cli/commands/agent.ts
2126
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";
2127
3573
  function print() {
2128
3574
  const s = resolveSettings();
2129
3575
  const saved = readSettings();
@@ -2165,13 +3611,13 @@ async function config(args) {
2165
3611
  if (!process.stdin.isTTY || !process.stdout.isTTY)
2166
3612
  return print();
2167
3613
  const s = resolveSettings();
2168
- const name = await p.text({ message: t("config.name"), initialValue: s.name, validate: (v) => v && v.trim() ? undefined : "—" });
2169
- 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))
2170
3616
  return;
2171
- const gpu = await p.confirm({ message: t("config.gpu"), initialValue: s.gpu });
2172
- if (p.isCancel(gpu))
3617
+ const gpu = await p2.confirm({ message: t("config.gpu"), initialValue: s.gpu });
3618
+ if (p2.isCancel(gpu))
2173
3619
  return;
2174
- const language = await p.select({
3620
+ const language = await p2.select({
2175
3621
  message: t("config.language"),
2176
3622
  initialValue: readSettings().language ?? "auto",
2177
3623
  options: [
@@ -2180,7 +3626,7 @@ async function config(args) {
2180
3626
  { value: "en", label: "English" }
2181
3627
  ]
2182
3628
  });
2183
- if (p.isCancel(language))
3629
+ if (p2.isCancel(language))
2184
3630
  return;
2185
3631
  saveSettings({ name: String(name).trim().slice(0, 40), gpu: !!gpu, language });
2186
3632
  resetLang();
@@ -2188,10 +3634,10 @@ async function config(args) {
2188
3634
  log.detail(t("config.restart"));
2189
3635
  }
2190
3636
 
2191
- // packages/hypeframe/src/cli/commands/doctor.ts
2192
- import { spawnSync as spawnSync2 } from "node:child_process";
2193
- import fs13 from "node:fs";
2194
- import path10 from "node:path";
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";
2195
3641
  var mark = { ok: color.ok(icon.ok), warn: color.warn(icon.warn), error: color.error(icon.error) };
2196
3642
  async function reach(url) {
2197
3643
  const t0 = Date.now();
@@ -2220,12 +3666,12 @@ async function doctor(args) {
2220
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")}` : ""}` });
2221
3667
  }
2222
3668
  try {
2223
- const probe = path10.join(dataDir(), `.probe-${process.pid}`);
2224
- fs13.writeFileSync(probe, "x");
2225
- fs13.rmSync(probe);
2226
- const st = fs13.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());
2227
3673
  const free = st.bavail * st.bsize;
2228
- show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size: 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) })}` });
2229
3675
  } catch (e) {
2230
3676
  show({ label: t("doctor.disk"), result: "error", detail: e.message });
2231
3677
  }
@@ -2234,7 +3680,7 @@ async function doctor(args) {
2234
3680
  const canDownload = !!FFMPEG_PINNED[`${process.platform}-${process.arch}`];
2235
3681
  show({ label: "ffmpeg", result: canDownload ? "warn" : "error", detail: canDownload ? t("doctor.ffmpegLater") : t("doctor.noFfmpeg") });
2236
3682
  } else {
2237
- const r = spawnSync2(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
3683
+ const r = spawnSync4(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
2238
3684
  const v = /ffmpeg version (\S+)/.exec(r.stdout || "")?.[1];
2239
3685
  show({ label: "ffmpeg", result: v ? "ok" : "error", detail: v || t("doctor.noFfmpeg") });
2240
3686
  }
@@ -2266,22 +3712,22 @@ async function doctor(args) {
2266
3712
  return checks;
2267
3713
  }
2268
3714
 
2269
- // packages/hypeframe/src/cli/commands/history.ts
2270
- import fs14 from "node:fs";
2271
- import path11 from "node:path";
2272
- 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) {
2273
3719
  const root = renderDir();
2274
3720
  const since = Date.now() - hours * 3600000;
2275
3721
  const out = [];
2276
- for (const name of fs14.readdirSync(root)) {
3722
+ for (const name of fs20.readdirSync(root)) {
2277
3723
  if (!JOB_ID.test(name))
2278
3724
  continue;
2279
3725
  try {
2280
- const j = JSON.parse(fs14.readFileSync(path11.join(root, name, "status.json"), "utf8"));
3726
+ const j = JSON.parse(fs20.readFileSync(path16.join(root, name, "status.json"), "utf8"));
2281
3727
  if ((j.diperbarui || j.dibuat) < since)
2282
3728
  continue;
2283
- const f = j.hasilBerkas ? path11.join(root, name, j.hasilBerkas) : null;
2284
- out.push({ job: j, file: f && fs14.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 });
2285
3731
  } catch {}
2286
3732
  }
2287
3733
  return out.sort((a, b) => (b.job.diperbarui || 0) - (a.job.diperbarui || 0));
@@ -2291,12 +3737,12 @@ function formatItem({ job: j, file }) {
2291
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);
2292
3738
  const kind = j.tiket.jenis === "klip" ? t("render.kindClip") : t("render.kindVideo");
2293
3739
  const took = j.selesaiPada && j.mulaiPada ? ` ${color.muted(icon.dot)} ${seconds(j.selesaiPada - j.mulaiPada)}` : "";
2294
- 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}%`);
2295
3741
  return `${color.muted(time2(j.diperbarui || j.dibuat))} ${mark} ${kind} ${color.muted(`${j.tiket.w}×${j.tiket.h}`)} ${detail}${file ? `
2296
3742
  ${color.muted(icon.detail)} ${color.muted(file)}` : ""}`;
2297
3743
  }
2298
3744
  function history() {
2299
- const items = readHistory();
3745
+ const items = readHistory2();
2300
3746
  console.log("");
2301
3747
  if (!items.length)
2302
3748
  console.log(` ${color.muted(t("history.empty"))}`);
@@ -2306,41 +3752,41 @@ function history() {
2306
3752
  return items;
2307
3753
  }
2308
3754
 
2309
- // packages/hypeframe/src/cli/commands/maintenance.ts
2310
- import { spawnSync as spawnSync3 } from "node:child_process";
2311
- import fs15 from "node:fs";
3755
+ // src/cli/commands/maintenance.ts
3756
+ import { spawnSync as spawnSync5 } from "node:child_process";
3757
+ import fs21 from "node:fs";
2312
3758
  import os4 from "node:os";
2313
- import path12 from "node:path";
3759
+ import path17 from "node:path";
2314
3760
  async function clean() {
2315
3761
  if (runningPid()) {
2316
3762
  log.warn(t("clean.running"));
2317
3763
  return;
2318
3764
  }
2319
- const targets = [path12.join(cacheDir(), "chrome"), path12.join(cacheDir(), "halaman"), path12.join(logDir(), "hypeframe.log.1")];
2320
- for (const job of fs15.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())) {
2321
3767
  if (!JOB_ID.test(job))
2322
3768
  continue;
2323
3769
  try {
2324
- const s = JSON.parse(fs15.readFileSync(path12.join(renderDir(), job, "status.json"), "utf8")).status;
3770
+ const s = JSON.parse(fs21.readFileSync(path17.join(renderDir(), job, "status.json"), "utf8")).status;
2325
3771
  if (s === "gagal" || s === "batal" || s === "unggah")
2326
- targets.push(path12.join(renderDir(), job));
3772
+ targets.push(path17.join(renderDir(), job));
2327
3773
  } catch {
2328
- targets.push(path12.join(renderDir(), job));
3774
+ targets.push(path17.join(renderDir(), job));
2329
3775
  }
2330
3776
  }
2331
3777
  let freed = 0;
2332
3778
  for (const p of targets) {
2333
3779
  freed += await sizeOf(p);
2334
- fs15.rmSync(p, { recursive: true, force: true });
3780
+ fs21.rmSync(p, { recursive: true, force: true });
2335
3781
  }
2336
- log.ok(t("clean.done", { size: bytes(freed) }));
3782
+ log.ok(t("clean.done", { size: bytes2(freed) }));
2337
3783
  }
2338
3784
  function report() {
2339
3785
  const s = resolveSettings();
2340
3786
  const a = readAccount();
2341
3787
  let recent = "";
2342
3788
  try {
2343
- recent = fs15.readFileSync(path12.join(logDir(), "hypeframe.log"), "utf8").split(`
3789
+ recent = fs21.readFileSync(path17.join(logDir(), "hypeframe.log"), "utf8").split(`
2344
3790
  `).slice(-400).join(`
2345
3791
  `);
2346
3792
  } catch {
@@ -2349,7 +3795,7 @@ function report() {
2349
3795
  const lines = [
2350
3796
  `hypeframe ${VERSION}`,
2351
3797
  `created ${new Date().toISOString()}`,
2352
- `${runtimeLabel()} · ${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`,
2353
3799
  `gateway ${s.gateway}`,
2354
3800
  `web ${s.web}`,
2355
3801
  `gpu ${s.gpu}`,
@@ -2361,8 +3807,8 @@ function report() {
2361
3807
  recent
2362
3808
  ];
2363
3809
  const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
2364
- const file = path12.join(dataDir(), `laporan-${stamp}.txt`);
2365
- fs15.writeFileSync(file, mask(lines.join(`
3810
+ const file = path17.join(dataDir(), `laporan-${stamp}.txt`);
3811
+ fs21.writeFileSync(file, mask(lines.join(`
2366
3812
  `)), { mode: 384 });
2367
3813
  log.ok(t("report.done", { file }));
2368
3814
  log.detail(t("report.hint"));
@@ -2376,7 +3822,7 @@ function update() {
2376
3822
  }
2377
3823
  log.info(t("update.running"));
2378
3824
  const win = process.platform === "win32";
2379
- const r = isStandalone() ? win ? spawnSync3("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_URL}.ps1 | iex`], { stdio: "inherit" }) : spawnSync3("bash", ["-c", `curl -fsSL ${INSTALL_URL} | bash`], { stdio: "inherit" }) : spawnSync3("npm", ["i", "-g", "hypeframe@latest"], { stdio: "inherit", shell: win });
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 });
2380
3826
  if (r.status === 0)
2381
3827
  log.ok(t("update.done"));
2382
3828
  else
@@ -2390,15 +3836,15 @@ function openWeb(args) {
2390
3836
  log.warn(t("pair.badWeb"));
2391
3837
  }
2392
3838
 
2393
- // packages/hypeframe/src/cli/commands/status.ts
2394
- import fs16 from "node:fs";
2395
- import path13 from "node:path";
3839
+ // src/cli/commands/status.ts
3840
+ import fs22 from "node:fs";
3841
+ import path18 from "node:path";
2396
3842
  function statusRows(args) {
2397
3843
  const s = resolveSettings(args?.flags);
2398
3844
  const a = readAccount();
2399
3845
  const pid = runningPid();
2400
- const chrome = findChrome() || fs16.existsSync(path13.join(cacheDir(), "chrome"));
2401
- const recent = readHistory();
3846
+ const chrome = findChrome() || fs22.existsSync(path18.join(cacheDir(), "chrome"));
3847
+ const recent = readHistory2();
2402
3848
  const k = (key) => color.muted(t(key));
2403
3849
  return [
2404
3850
  [k("status.account"), a && a.gateway === s.gateway ? `${color.ok(icon.ok)} ${maskEmail(a.email)}` : `${color.warn(icon.warn)} ${t("status.notPaired")}`],
@@ -2415,8 +3861,8 @@ function status(args) {
2415
3861
  console.log("");
2416
3862
  }
2417
3863
 
2418
- // packages/hypeframe/src/cli/menu.ts
2419
- import * as p2 from "@clack/prompts";
3864
+ // src/cli/menu.ts
3865
+ import * as p3 from "@clack/prompts";
2420
3866
  async function menu(args) {
2421
3867
  process.stdout.write(banner());
2422
3868
  console.log("");
@@ -2426,14 +3872,17 @@ async function menu(args) {
2426
3872
  const s = resolveSettings(args.flags);
2427
3873
  const paired = !!readAccount() && readAccount()?.gateway === s.gateway;
2428
3874
  const running = !!runningPid();
2429
- const choice = await p2.select({
3875
+ const choice = await p3.select({
2430
3876
  message: t("menu.question"),
2431
3877
  options: [
2432
3878
  { value: "start", label: color.brand(t("menu.start")), hint: running ? t("status.running", { pid: runningPid() ?? "" }) : paired ? undefined : t("menu.startPair") },
2433
3879
  { value: "open", label: t("menu.open"), hint: s.web.replace(/^https?:\/\//, "") },
2434
3880
  { value: "bench", label: t("menu.bench") },
2435
3881
  { value: "history", label: t("menu.history") },
2436
- { 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
+ })() },
2437
3886
  { value: "autostart", label: t("menu.autostart"), hint: autostartEnabled() ? t("status.on") : t("status.off") },
2438
3887
  { value: "config", label: t("menu.config") },
2439
3888
  { value: "doctor", label: t("menu.doctor") },
@@ -2444,15 +3893,15 @@ async function menu(args) {
2444
3893
  { value: "exit", label: color.muted(t("menu.exit")) }
2445
3894
  ]
2446
3895
  });
2447
- if (p2.isCancel(choice) || choice === "exit") {
2448
- p2.outro(color.muted(t("menu.bye")));
3896
+ if (p3.isCancel(choice) || choice === "exit") {
3897
+ p3.outro(color.muted(t("menu.bye")));
2449
3898
  return;
2450
3899
  }
2451
3900
  try {
2452
3901
  switch (choice) {
2453
3902
  case "start":
2454
3903
  if (running) {
2455
- p2.log.warn(t("engine.running"));
3904
+ p3.log.warn(t("engine.running"));
2456
3905
  break;
2457
3906
  }
2458
3907
  await start(args, { fromMenu: true });
@@ -2466,18 +3915,18 @@ async function menu(args) {
2466
3915
  case "history": {
2467
3916
  const items = history();
2468
3917
  if (items.some((i) => i.file)) {
2469
- const go = await p2.confirm({ message: t("history.openFolder"), initialValue: false });
3918
+ const go = await p3.confirm({ message: t("history.openFolder"), initialValue: false });
2470
3919
  if (go === true)
2471
3920
  openFolder(renderDir());
2472
3921
  }
2473
3922
  break;
2474
3923
  }
2475
3924
  case "agent":
2476
- p2.log.message(`${color.ai("✦")} ${t("agent.soon")}`);
3925
+ await agentMenu();
2477
3926
  break;
2478
3927
  case "autostart": {
2479
- const on = await p2.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
2480
- if (!p2.isCancel(on))
3928
+ const on = await p3.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
3929
+ if (!p3.isCancel(on))
2481
3930
  autostart(on ? "on" : "off");
2482
3931
  break;
2483
3932
  }
@@ -2488,7 +3937,7 @@ async function menu(args) {
2488
3937
  await doctor(args);
2489
3938
  break;
2490
3939
  case "clean": {
2491
- const ok = await p2.confirm({ message: t("clean.question"), initialValue: true });
3940
+ const ok = await p3.confirm({ message: t("clean.question"), initialValue: true });
2492
3941
  if (ok === true)
2493
3942
  await clean();
2494
3943
  break;
@@ -2503,19 +3952,19 @@ async function menu(args) {
2503
3952
  await login(args);
2504
3953
  break;
2505
3954
  case "logout": {
2506
- const ok = await p2.confirm({ message: t("confirm.logout"), initialValue: false });
3955
+ const ok = await p3.confirm({ message: t("confirm.logout"), initialValue: false });
2507
3956
  if (ok === true)
2508
3957
  logout();
2509
3958
  break;
2510
3959
  }
2511
3960
  }
2512
3961
  } catch (e) {
2513
- p2.log.error(`${icon.error} ${e.message}`);
3962
+ p3.log.error(`${icon.error} ${e.message}`);
2514
3963
  }
2515
3964
  }
2516
3965
  }
2517
3966
 
2518
- // packages/hypeframe/src/index.ts
3967
+ // src/index.ts
2519
3968
  function help() {
2520
3969
  const rows = [
2521
3970
  ["start", t("help.start")],
@@ -2525,6 +3974,7 @@ function help() {
2525
3974
  ["open", t("help.open")],
2526
3975
  ["doctor", t("help.doctor")],
2527
3976
  ["bench", t("help.bench")],
3977
+ ["agent list|add|login|remove", t("help.agent")],
2528
3978
  ["history", t("help.history")],
2529
3979
  ["autostart on|off", t("help.autostart")],
2530
3980
  ["config", t("help.config")],
@@ -2566,6 +4016,8 @@ var COMMANDS = {
2566
4016
  process.exitCode = checks.some((c) => c.result === "error") ? 1 : 0;
2567
4017
  },
2568
4018
  bench: (a) => bench(a),
4019
+ agent: (a) => agentCommand(a),
4020
+ "mcp-bridge": () => runMcpBridge(),
2569
4021
  history: () => history(),
2570
4022
  autostart: (a) => autostart(a.rest[0]),
2571
4023
  config: (a) => config(a),