hypeframe 0.8.2 → 0.9.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.
- package/README.md +2 -1
- package/dist/index.js +712 -462
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -243,6 +243,7 @@ var id = {
|
|
|
243
243
|
"agentLog.refused": "ditolak",
|
|
244
244
|
"agentLog.option": "{agent}: {what} diganti ke {value}",
|
|
245
245
|
"agentLog.stopped": "✦ {agent} berhenti (kode {code}). Obrolan baru menyalakannya lagi.",
|
|
246
|
+
"agentLog.account": "✦ Akun {agent} berganti: dimuat ulang, obrolan berikutnya memakai akun baru.",
|
|
246
247
|
"engine.agentsReady": "Asisten AI siap: {list}",
|
|
247
248
|
"engine.agentsNone": "Belum ada asisten AI. Pasang dari menu hypeframe > Asisten AI.",
|
|
248
249
|
"engine.statusHint": "Tekan Enter kapan saja untuk melihat status.",
|
|
@@ -513,6 +514,7 @@ var en = {
|
|
|
513
514
|
"agentLog.refused": "refused",
|
|
514
515
|
"agentLog.option": "{agent}: {what} changed to {value}",
|
|
515
516
|
"agentLog.stopped": "✦ {agent} stopped (code {code}). A new chat starts it again.",
|
|
517
|
+
"agentLog.account": "✦ {agent} account changed: reloaded, the next chat uses the new account.",
|
|
516
518
|
"engine.agentsReady": "AI assistants ready: {list}",
|
|
517
519
|
"engine.agentsNone": "No AI assistant yet. Add one from the hypeframe menu > AI assistant.",
|
|
518
520
|
"engine.statusHint": "Press Enter at any time to see the status.",
|
|
@@ -797,7 +799,7 @@ import readline3 from "node:readline";
|
|
|
797
799
|
|
|
798
800
|
// ../protocol/src/index.ts
|
|
799
801
|
var PROTOCOL_VERSION = 1;
|
|
800
|
-
var ALLOWED_KINDS = ["status", "kunci", "agen.mulai", "agen.kirim", "agen.izin", "agen.batal", "agen.opsi", "agen.riwayat", "render.relai"];
|
|
802
|
+
var ALLOWED_KINDS = ["status", "kunci", "agen.mulai", "agen.kirim", "agen.izin", "agen.batal", "agen.opsi", "agen.riwayat", "agen.akun", "render.relai"];
|
|
801
803
|
var CloseCode = {
|
|
802
804
|
BadHello: 4001,
|
|
803
805
|
Replaced: 4002,
|
|
@@ -820,12 +822,12 @@ var EngineError = {
|
|
|
820
822
|
|
|
821
823
|
// src/agent/service.ts
|
|
822
824
|
import crypto3 from "node:crypto";
|
|
823
|
-
import
|
|
824
|
-
import
|
|
825
|
+
import fs11 from "node:fs";
|
|
826
|
+
import path8 from "node:path";
|
|
825
827
|
// package.json
|
|
826
828
|
var package_default = {
|
|
827
829
|
name: "hypeframe",
|
|
828
|
-
version: "0.
|
|
830
|
+
version: "0.9.0",
|
|
829
831
|
description: "Local engine for HypeFrame Web: code clips, video renders and AI agents run on your own machine; the web is just the view.",
|
|
830
832
|
keywords: [
|
|
831
833
|
"hypeframe",
|
|
@@ -1039,6 +1041,7 @@ function writeHelpers() {
|
|
|
1039
1041
|
const open = `#!/bin/sh
|
|
1040
1042
|
# HypeFrame: open a link in the phone's browser (the engine watches this file)
|
|
1041
1043
|
[ -n "$1" ] || exit 0
|
|
1044
|
+
[ -n "$HF_TANPA_BUKA" ] && exit 0
|
|
1042
1045
|
printf '%s\\n' "$1" >> "${openFile()}"
|
|
1043
1046
|
`;
|
|
1044
1047
|
fs7.writeFileSync(path4.join(bin, "xdg-open"), open, { mode: 493 });
|
|
@@ -1109,10 +1112,8 @@ function watchOpenRequests(open, everyMs = 1000) {
|
|
|
1109
1112
|
return () => clearInterval(timer);
|
|
1110
1113
|
}
|
|
1111
1114
|
|
|
1112
|
-
// src/agent/
|
|
1113
|
-
import
|
|
1114
|
-
import fs8 from "node:fs";
|
|
1115
|
-
import path5 from "node:path";
|
|
1115
|
+
// src/agent/login.ts
|
|
1116
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1116
1117
|
|
|
1117
1118
|
// src/agent/acp.ts
|
|
1118
1119
|
import { spawn } from "node:child_process";
|
|
@@ -1127,12 +1128,17 @@ class RpcError extends Error {
|
|
|
1127
1128
|
this.data = data;
|
|
1128
1129
|
}
|
|
1129
1130
|
}
|
|
1130
|
-
function agentSpawn(agent, env = {}, extraArgs = []) {
|
|
1131
|
+
function agentSpawn(agent, env = {}, extraArgs = [], opts = {}) {
|
|
1132
|
+
const all = [...agent.launch.args, ...extraArgs];
|
|
1133
|
+
const inTerminal = (cmd) => `stty cols 400 rows 50 2>/dev/null; exec ${[cmd, ...all].map(shQuote).join(" ")}`;
|
|
1131
1134
|
if (agent.launch.linux) {
|
|
1132
|
-
const [cmd, args] = linuxCommand(agent.launch.cmd,
|
|
1135
|
+
const [cmd, args] = opts.pty ? linuxCommand("/usr/bin/script", ["-qfec", inTerminal(agent.launch.cmd), "/dev/null"], { ...agent.launch.env, ...env }) : linuxCommand(agent.launch.cmd, all, { ...agent.launch.env, ...env });
|
|
1133
1136
|
return [cmd, args, { ...process.env }];
|
|
1134
1137
|
}
|
|
1135
|
-
|
|
1138
|
+
const childEnv = { ...process.env, ...agent.launch.env, ...env };
|
|
1139
|
+
if (opts.pty && process.platform === "linux" && onPath("script"))
|
|
1140
|
+
return ["script", ["-qfec", inTerminal(agent.launch.cmd), "/dev/null"], childEnv];
|
|
1141
|
+
return [agent.launch.cmd, all, childEnv];
|
|
1136
1142
|
}
|
|
1137
1143
|
|
|
1138
1144
|
class AcpProcess extends EventEmitter {
|
|
@@ -1250,7 +1256,375 @@ class AcpProcess extends EventEmitter {
|
|
|
1250
1256
|
}
|
|
1251
1257
|
}
|
|
1252
1258
|
|
|
1259
|
+
// src/agent/store.ts
|
|
1260
|
+
import fs8 from "node:fs";
|
|
1261
|
+
import path5 from "node:path";
|
|
1262
|
+
function setReady(id, ready) {
|
|
1263
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
1264
|
+
if (a)
|
|
1265
|
+
writeInstalled({ ...a, ready });
|
|
1266
|
+
}
|
|
1267
|
+
var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
1268
|
+
var folder = (id) => {
|
|
1269
|
+
if (typeof id !== "string" || !AGENT_ID.test(id))
|
|
1270
|
+
throw new Error(`Invalid agent id: ${JSON.stringify(String(id)).slice(0, 60)}`);
|
|
1271
|
+
return path5.join(agentDir(), id);
|
|
1272
|
+
};
|
|
1273
|
+
function readInstalled() {
|
|
1274
|
+
const out = [];
|
|
1275
|
+
for (const id of fs8.readdirSync(agentDir())) {
|
|
1276
|
+
if (!AGENT_ID.test(id))
|
|
1277
|
+
continue;
|
|
1278
|
+
try {
|
|
1279
|
+
const a = JSON.parse(fs8.readFileSync(path5.join(folder(id), "agent.json"), "utf8"));
|
|
1280
|
+
if (a.id === id && a.launch?.cmd)
|
|
1281
|
+
out.push(a);
|
|
1282
|
+
} catch {}
|
|
1283
|
+
}
|
|
1284
|
+
return out;
|
|
1285
|
+
}
|
|
1286
|
+
function writeInstalled(a) {
|
|
1287
|
+
fs8.mkdirSync(folder(a.id), { recursive: true });
|
|
1288
|
+
const f = path5.join(folder(a.id), "agent.json");
|
|
1289
|
+
fs8.writeFileSync(`${f}.tmp`, JSON.stringify(a, null, 2));
|
|
1290
|
+
fs8.renameSync(`${f}.tmp`, f);
|
|
1291
|
+
}
|
|
1292
|
+
function removeAgent(id) {
|
|
1293
|
+
fs8.rmSync(folder(id), { recursive: true, force: true });
|
|
1294
|
+
}
|
|
1295
|
+
function agentEnv(id) {
|
|
1296
|
+
try {
|
|
1297
|
+
return JSON.parse(fs8.readFileSync(path5.join(folder(id), "env.json"), "utf8"));
|
|
1298
|
+
} catch {
|
|
1299
|
+
return {};
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
var SECRET_NAME = /KEY|TOKEN|SECRET|PASSWORD/i;
|
|
1303
|
+
function forgetAgentSecrets(id) {
|
|
1304
|
+
const gone = Object.keys(agentEnv(id)).filter((k) => SECRET_NAME.test(k));
|
|
1305
|
+
removeAgentEnv(id, gone);
|
|
1306
|
+
return gone;
|
|
1307
|
+
}
|
|
1308
|
+
function removeAgentEnv(id, names) {
|
|
1309
|
+
const env = agentEnv(id);
|
|
1310
|
+
if (!names.some((k) => (k in env)))
|
|
1311
|
+
return;
|
|
1312
|
+
for (const k of names)
|
|
1313
|
+
delete env[k];
|
|
1314
|
+
const f = path5.join(folder(id), "env.json");
|
|
1315
|
+
fs8.writeFileSync(`${f}.tmp`, JSON.stringify(env), { mode: 384 });
|
|
1316
|
+
fs8.renameSync(`${f}.tmp`, f);
|
|
1317
|
+
}
|
|
1318
|
+
function saveAgentEnv(id, env) {
|
|
1319
|
+
fs8.mkdirSync(folder(id), { recursive: true });
|
|
1320
|
+
const f = path5.join(folder(id), "env.json");
|
|
1321
|
+
fs8.writeFileSync(`${f}.tmp`, JSON.stringify({ ...agentEnv(id), ...env }), { mode: 384 });
|
|
1322
|
+
fs8.renameSync(`${f}.tmp`, f);
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
// src/agent/login.ts
|
|
1326
|
+
var SIGN_IN = /https?:\/\/[^\s"'<>]{8,2000}/g;
|
|
1327
|
+
var looksLikeSignIn = (u) => /oauth|auth|login|signin|sign-in|device|accounts\./i.test(u);
|
|
1328
|
+
function linkScanner(found) {
|
|
1329
|
+
const seen = new Set;
|
|
1330
|
+
let rest = "";
|
|
1331
|
+
return (text) => {
|
|
1332
|
+
rest += text;
|
|
1333
|
+
const end = rest.lastIndexOf(`
|
|
1334
|
+
`);
|
|
1335
|
+
if (end < 0)
|
|
1336
|
+
return void (rest = rest.slice(-4096));
|
|
1337
|
+
const lines = rest.slice(0, end);
|
|
1338
|
+
rest = rest.slice(end + 1);
|
|
1339
|
+
for (const u of lines.match(SIGN_IN) ?? [])
|
|
1340
|
+
if (looksLikeSignIn(u) && !seen.has(u))
|
|
1341
|
+
seen.add(u), found(u);
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
function runAttached(cmd, args, env) {
|
|
1345
|
+
return new Promise((done) => {
|
|
1346
|
+
const child = spawn2(cmd, args, { stdio: "inherit", env });
|
|
1347
|
+
child.on("error", () => done(-1));
|
|
1348
|
+
child.on("exit", (code) => done(code));
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
async function keyFromShell(name, io) {
|
|
1352
|
+
const value = process.env[name];
|
|
1353
|
+
if (!value)
|
|
1354
|
+
return null;
|
|
1355
|
+
if (io.confirm)
|
|
1356
|
+
return await io.confirm(t("agent.keyFromShellAsk", { name })) ? value : null;
|
|
1357
|
+
io.say(t("agent.keyFromShell", { name }));
|
|
1358
|
+
return value;
|
|
1359
|
+
}
|
|
1360
|
+
async function checkReady(id) {
|
|
1361
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
1362
|
+
if (!a)
|
|
1363
|
+
return false;
|
|
1364
|
+
const proc = new AcpProcess;
|
|
1365
|
+
try {
|
|
1366
|
+
await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
1367
|
+
await proc.request("session/new", { cwd: projectDir("_cek"), mcpServers: [] }, 90000);
|
|
1368
|
+
setReady(id, true);
|
|
1369
|
+
return true;
|
|
1370
|
+
} catch {
|
|
1371
|
+
setReady(id, false);
|
|
1372
|
+
return false;
|
|
1373
|
+
} finally {
|
|
1374
|
+
await proc.stop();
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
var isKey = (m) => m.type === "env_var" || !!m.varName;
|
|
1378
|
+
function pick(methods) {
|
|
1379
|
+
return methods.find((m) => m.type === "terminal") ?? methods.find((m) => (!m.type || m.type === "agent") && !isKey(m)) ?? methods.find(isKey);
|
|
1380
|
+
}
|
|
1381
|
+
async function logoutAgent(id) {
|
|
1382
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
1383
|
+
if (!a)
|
|
1384
|
+
throw new Error(`Agent ${id} is not installed`);
|
|
1385
|
+
let signedOut = false;
|
|
1386
|
+
const proc = new AcpProcess;
|
|
1387
|
+
try {
|
|
1388
|
+
const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
1389
|
+
if (init.agentCapabilities?.auth?.logout)
|
|
1390
|
+
signedOut = await proc.request("logout", {}, 60000).then(() => true, () => false) || false;
|
|
1391
|
+
} finally {
|
|
1392
|
+
await proc.stop();
|
|
1393
|
+
}
|
|
1394
|
+
const keys = forgetAgentSecrets(id).length > 0;
|
|
1395
|
+
if (!signedOut && !keys)
|
|
1396
|
+
return "unsupported";
|
|
1397
|
+
setReady(id, false);
|
|
1398
|
+
return signedOut ? "signed-out" : "key-removed";
|
|
1399
|
+
}
|
|
1400
|
+
async function loginAgent(id, io) {
|
|
1401
|
+
const a = readInstalled().find((x) => x.id === id);
|
|
1402
|
+
if (!a)
|
|
1403
|
+
throw new Error(`Agent ${id} is not installed`);
|
|
1404
|
+
const proc = new AcpProcess;
|
|
1405
|
+
let method;
|
|
1406
|
+
if (io.link)
|
|
1407
|
+
proc.on("stderr", linkScanner(io.link));
|
|
1408
|
+
try {
|
|
1409
|
+
const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
1410
|
+
method = pick(init.authMethods ?? []);
|
|
1411
|
+
if (method && (!method.type || method.type === "agent") && !isKey(method))
|
|
1412
|
+
await proc.request("authenticate", { methodId: method.id }, 10 * 60000);
|
|
1413
|
+
} finally {
|
|
1414
|
+
await proc.stop();
|
|
1415
|
+
}
|
|
1416
|
+
if (method?.type === "terminal") {
|
|
1417
|
+
io.say(method.name || method.description || id);
|
|
1418
|
+
const [cmd, args, env] = agentSpawn(a, { ...agentEnv(id), ...method.env ?? {} }, method.args ?? []);
|
|
1419
|
+
if (await runAttached(cmd, args, env) !== 0)
|
|
1420
|
+
return setReady(id, false), false;
|
|
1421
|
+
} else if (method && isKey(method)) {
|
|
1422
|
+
const name = method.varName || method.id;
|
|
1423
|
+
const value = await keyFromShell(name, io) || await io.ask(name);
|
|
1424
|
+
if (!value)
|
|
1425
|
+
return false;
|
|
1426
|
+
saveAgentEnv(id, { [name]: value.trim() });
|
|
1427
|
+
}
|
|
1428
|
+
return checkReady(id);
|
|
1429
|
+
}
|
|
1430
|
+
var ANSI = /\x1b\[[0-9;?<>=]*[A-Za-z]|\x1b\][^\x07]*\x07|\r/g;
|
|
1431
|
+
var CODE_PROMPT = /paste the authorization code|authorization code|enter the code/i;
|
|
1432
|
+
var remote = new Map;
|
|
1433
|
+
|
|
1434
|
+
class RemoteLogin {
|
|
1435
|
+
id;
|
|
1436
|
+
state = { tahap: "mulai" };
|
|
1437
|
+
child;
|
|
1438
|
+
proc;
|
|
1439
|
+
text = "";
|
|
1440
|
+
ended = false;
|
|
1441
|
+
timer;
|
|
1442
|
+
constructor(id) {
|
|
1443
|
+
this.id = id;
|
|
1444
|
+
}
|
|
1445
|
+
async start() {
|
|
1446
|
+
const a = readInstalled().find((x) => x.id === this.id);
|
|
1447
|
+
if (!a)
|
|
1448
|
+
return this.fail("Agen belum dipasang di mesin ini.");
|
|
1449
|
+
if (a.launch.linux)
|
|
1450
|
+
writeHelpers();
|
|
1451
|
+
const env = { ...agentEnv(this.id), HF_TANPA_BUKA: "1" };
|
|
1452
|
+
this.timer = setTimeout(() => this.cancel("Waktu masuk habis (10 menit). Coba lagi."), 10 * 60000);
|
|
1453
|
+
this.timer.unref?.();
|
|
1454
|
+
const scan = linkScanner((u) => this.link(u));
|
|
1455
|
+
const proc = this.proc = new AcpProcess;
|
|
1456
|
+
proc.on("stderr", scan);
|
|
1457
|
+
let method;
|
|
1458
|
+
try {
|
|
1459
|
+
const init = await proc.start(a, projectDir("_cek"), env);
|
|
1460
|
+
method = pick(init.authMethods ?? []);
|
|
1461
|
+
if (method && (!method.type || method.type === "agent") && !isKey(method)) {
|
|
1462
|
+
this.state = { ...this.state, cara: "browser" };
|
|
1463
|
+
await proc.request("authenticate", { methodId: method.id }, 10 * 60000);
|
|
1464
|
+
await proc.stop();
|
|
1465
|
+
return this.finish();
|
|
1466
|
+
}
|
|
1467
|
+
} catch (e) {
|
|
1468
|
+
await proc.stop();
|
|
1469
|
+
return this.fail(e instanceof Error ? e.message : String(e));
|
|
1470
|
+
}
|
|
1471
|
+
await proc.stop();
|
|
1472
|
+
if (method?.type !== "terminal")
|
|
1473
|
+
return this.fail("Agen ini masuk dengan kunci API, bukan akun. Atur kuncinya di perangkat yang menjalankan mesin.");
|
|
1474
|
+
this.state = { ...this.state, cara: "kode" };
|
|
1475
|
+
const [cmd, args, childEnv] = agentSpawn(a, { ...env, ...method.env ?? {} }, method.args ?? [], { pty: true });
|
|
1476
|
+
const child = this.child = spawn2(cmd, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
1477
|
+
const feed = (d) => {
|
|
1478
|
+
const t = String(d).replace(ANSI, "");
|
|
1479
|
+
this.text = (this.text + t).slice(-8000);
|
|
1480
|
+
scan(t);
|
|
1481
|
+
if (CODE_PROMPT.test(this.text) && (this.state.tahap === "tautan" || this.state.tahap === "mulai") && this.state.tautan)
|
|
1482
|
+
this.state = { ...this.state, tahap: "kode" };
|
|
1483
|
+
};
|
|
1484
|
+
child.stdout?.on("data", feed);
|
|
1485
|
+
child.stderr?.on("data", feed);
|
|
1486
|
+
child.stdin?.on("error", () => {
|
|
1487
|
+
return;
|
|
1488
|
+
});
|
|
1489
|
+
child.on("error", (e) => this.fail(e.message));
|
|
1490
|
+
child.on("exit", (code) => code === 0 ? void this.finish() : this.fail(lastLines(this.text) || `Masuk berhenti (kode ${code}).`));
|
|
1491
|
+
}
|
|
1492
|
+
link(u) {
|
|
1493
|
+
if (this.ended || this.state.tautan)
|
|
1494
|
+
return;
|
|
1495
|
+
this.state = { ...this.state, tautan: u, tahap: CODE_PROMPT.test(this.text) && this.state.cara === "kode" ? "kode" : "tautan" };
|
|
1496
|
+
}
|
|
1497
|
+
sendCode(code) {
|
|
1498
|
+
const k = code.trim().slice(0, 2000);
|
|
1499
|
+
if (!k || !this.child || this.state.tahap !== "kode")
|
|
1500
|
+
throw new Error("Belum ada yang menunggu kode. Mulai masuk lagi.");
|
|
1501
|
+
this.child.stdin?.write(`${k}\r`);
|
|
1502
|
+
this.state = { ...this.state, tahap: "cek" };
|
|
1503
|
+
}
|
|
1504
|
+
async finish() {
|
|
1505
|
+
if (this.ended)
|
|
1506
|
+
return;
|
|
1507
|
+
this.state = { ...this.state, tahap: "cek" };
|
|
1508
|
+
const ok = await checkReady(this.id);
|
|
1509
|
+
this.end(ok ? { tahap: "selesai" } : { tahap: "gagal", pesan: "Masuk selesai, tapi agen belum bisa membuka obrolan. Coba lagi." });
|
|
1510
|
+
}
|
|
1511
|
+
fail(pesan) {
|
|
1512
|
+
if (this.ended)
|
|
1513
|
+
return;
|
|
1514
|
+
setReady(this.id, false);
|
|
1515
|
+
this.end({ ...this.state, tahap: "gagal", pesan: pesan.slice(0, 400) });
|
|
1516
|
+
}
|
|
1517
|
+
cancel(pesan = "Masuk dibatalkan.") {
|
|
1518
|
+
this.child?.kill();
|
|
1519
|
+
this.proc?.stop();
|
|
1520
|
+
this.fail(pesan);
|
|
1521
|
+
}
|
|
1522
|
+
end(s) {
|
|
1523
|
+
this.ended = true;
|
|
1524
|
+
clearTimeout(this.timer);
|
|
1525
|
+
this.state = s;
|
|
1526
|
+
}
|
|
1527
|
+
get done() {
|
|
1528
|
+
return this.ended;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
function lastLines(t) {
|
|
1532
|
+
return t.split(`
|
|
1533
|
+
`).map((l) => l.trim()).filter((l) => l && !/^https?:\/\//.test(l)).slice(-2).join(" ").slice(0, 300);
|
|
1534
|
+
}
|
|
1535
|
+
function startRemoteLogin(id) {
|
|
1536
|
+
const old = remote.get(id);
|
|
1537
|
+
if (old && !old.done)
|
|
1538
|
+
return old.state;
|
|
1539
|
+
const r = new RemoteLogin(id);
|
|
1540
|
+
remote.set(id, r);
|
|
1541
|
+
r.start();
|
|
1542
|
+
return r.state;
|
|
1543
|
+
}
|
|
1544
|
+
var remoteLoginState = (id) => remote.get(id)?.state ?? null;
|
|
1545
|
+
function sendRemoteCode(id, code) {
|
|
1546
|
+
const r = remote.get(id);
|
|
1547
|
+
if (!r)
|
|
1548
|
+
throw new Error("Belum ada yang menunggu kode. Mulai masuk lagi.");
|
|
1549
|
+
r.sendCode(code);
|
|
1550
|
+
return r.state;
|
|
1551
|
+
}
|
|
1552
|
+
function cancelRemoteLogin(id) {
|
|
1553
|
+
const r = remote.get(id);
|
|
1554
|
+
if (r && !r.done)
|
|
1555
|
+
r.cancel();
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// src/agent/opencode.ts
|
|
1559
|
+
import fs9 from "node:fs";
|
|
1560
|
+
import path6 from "node:path";
|
|
1561
|
+
var OPENCODE = "opencode";
|
|
1562
|
+
var OPENCODE_KEY = "HF_OPENCODE_KEY";
|
|
1563
|
+
var PROVIDER = "hypeframe";
|
|
1564
|
+
var configFile = () => path6.join(dataDir(), "opencode.json");
|
|
1565
|
+
var cleanUrl = (u) => u.trim().replace(/\/+$/, "");
|
|
1566
|
+
function saveOpencodeApi(api) {
|
|
1567
|
+
const url = cleanUrl(api.url);
|
|
1568
|
+
if (!/^https?:\/\/[^\s/]+/i.test(url))
|
|
1569
|
+
throw new Error("The API address must start with http:// or https://");
|
|
1570
|
+
const models = [...new Set(api.models.map((m) => m.trim()).filter(Boolean))].slice(0, 50);
|
|
1571
|
+
if (!models.length)
|
|
1572
|
+
throw new Error("Pick at least one model");
|
|
1573
|
+
const key = api.key.trim();
|
|
1574
|
+
const config = {
|
|
1575
|
+
$schema: "https://opencode.ai/config.json",
|
|
1576
|
+
provider: {
|
|
1577
|
+
[PROVIDER]: {
|
|
1578
|
+
npm: "@ai-sdk/openai-compatible",
|
|
1579
|
+
name: (api.name || new URL(url).hostname).slice(0, 60),
|
|
1580
|
+
options: { baseURL: url, ...key ? { apiKey: `{env:${OPENCODE_KEY}}` } : {} },
|
|
1581
|
+
models: Object.fromEntries(models.map((m) => [m, { name: m }]))
|
|
1582
|
+
}
|
|
1583
|
+
},
|
|
1584
|
+
model: `${PROVIDER}/${models[0]}`
|
|
1585
|
+
};
|
|
1586
|
+
const f = configFile();
|
|
1587
|
+
fs9.writeFileSync(`${f}.tmp`, `${JSON.stringify(config, null, 2)}
|
|
1588
|
+
`, { mode: 384 });
|
|
1589
|
+
fs9.renameSync(`${f}.tmp`, f);
|
|
1590
|
+
if (key)
|
|
1591
|
+
saveAgentEnv(OPENCODE, { [OPENCODE_KEY]: key, OPENCODE_CONFIG: f });
|
|
1592
|
+
else
|
|
1593
|
+
removeAgentEnv(OPENCODE, [OPENCODE_KEY]), saveAgentEnv(OPENCODE, { OPENCODE_CONFIG: f });
|
|
1594
|
+
return f;
|
|
1595
|
+
}
|
|
1596
|
+
function opencodeApi() {
|
|
1597
|
+
try {
|
|
1598
|
+
const c = JSON.parse(fs9.readFileSync(configFile(), "utf8"));
|
|
1599
|
+
const p = c?.provider?.[PROVIDER];
|
|
1600
|
+
if (!p?.options?.baseURL)
|
|
1601
|
+
return null;
|
|
1602
|
+
return { url: String(p.options.baseURL), name: String(p.name ?? ""), model: String(c.model ?? "").replace(`${PROVIDER}/`, "") };
|
|
1603
|
+
} catch {
|
|
1604
|
+
return null;
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
function removeOpencodeApi() {
|
|
1608
|
+
fs9.rmSync(configFile(), { force: true });
|
|
1609
|
+
removeAgentEnv(OPENCODE, [OPENCODE_KEY, "OPENCODE_CONFIG"]);
|
|
1610
|
+
}
|
|
1611
|
+
async function fetchApiModels(url, key, timeoutMs = 1e4) {
|
|
1612
|
+
try {
|
|
1613
|
+
const r = await fetch(`${cleanUrl(url)}/models`, { headers: key.trim() ? { authorization: `Bearer ${key.trim()}` } : {}, signal: AbortSignal.timeout(timeoutMs) });
|
|
1614
|
+
if (!r.ok)
|
|
1615
|
+
return [];
|
|
1616
|
+
const j = await r.json();
|
|
1617
|
+
const ids = (Array.isArray(j?.data) ? j.data : []).map((m) => typeof m?.id === "string" ? m.id : "").filter((x) => x && x.length < 200);
|
|
1618
|
+
return [...new Set(ids)].sort();
|
|
1619
|
+
} catch {
|
|
1620
|
+
return [];
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1253
1624
|
// src/agent/session.ts
|
|
1625
|
+
import crypto2 from "node:crypto";
|
|
1626
|
+
import fs10 from "node:fs";
|
|
1627
|
+
import path7 from "node:path";
|
|
1254
1628
|
var UNSAFE_MODE = /bypass|dont.?ask|accept.?edits|yolo|full.?access|danger/i;
|
|
1255
1629
|
var SAFE_MODES = ["default", "ask"];
|
|
1256
1630
|
var MAX_READ = 10 * 1024 * 1024;
|
|
@@ -1273,7 +1647,7 @@ function splitId(id) {
|
|
|
1273
1647
|
}
|
|
1274
1648
|
var lexists = (p) => {
|
|
1275
1649
|
try {
|
|
1276
|
-
|
|
1650
|
+
fs10.lstatSync(p);
|
|
1277
1651
|
return true;
|
|
1278
1652
|
} catch {
|
|
1279
1653
|
return false;
|
|
@@ -1282,16 +1656,16 @@ var lexists = (p) => {
|
|
|
1282
1656
|
function insideFolder(folder, p) {
|
|
1283
1657
|
if (typeof p !== "string" || !p)
|
|
1284
1658
|
return false;
|
|
1285
|
-
const abs =
|
|
1286
|
-
const rel =
|
|
1287
|
-
if (rel.startsWith("..") ||
|
|
1659
|
+
const abs = path7.resolve(folder, p);
|
|
1660
|
+
const rel = path7.relative(folder, abs);
|
|
1661
|
+
if (rel.startsWith("..") || path7.isAbsolute(rel))
|
|
1288
1662
|
return false;
|
|
1289
1663
|
let probe = abs;
|
|
1290
|
-
while (!lexists(probe) &&
|
|
1291
|
-
probe =
|
|
1664
|
+
while (!lexists(probe) && path7.dirname(probe) !== probe)
|
|
1665
|
+
probe = path7.dirname(probe);
|
|
1292
1666
|
try {
|
|
1293
|
-
const r =
|
|
1294
|
-
return !(r.startsWith("..") ||
|
|
1667
|
+
const r = path7.relative(fs10.realpathSync(folder), fs10.realpathSync(probe));
|
|
1668
|
+
return !(r.startsWith("..") || path7.isAbsolute(r));
|
|
1295
1669
|
} catch {
|
|
1296
1670
|
return false;
|
|
1297
1671
|
}
|
|
@@ -1348,8 +1722,8 @@ class AgentSessions {
|
|
|
1348
1722
|
}
|
|
1349
1723
|
this.o.onExit(agentId, code);
|
|
1350
1724
|
});
|
|
1351
|
-
const cwd =
|
|
1352
|
-
|
|
1725
|
+
const cwd = path7.join(agentDir(), agentId, "kerja");
|
|
1726
|
+
fs10.mkdirSync(cwd, { recursive: true });
|
|
1353
1727
|
const p = proc.start(agent, cwd, this.o.env?.(agentId) ?? {}, this.o.startTimeoutMs ?? 180000).then((init) => {
|
|
1354
1728
|
const entry = { proc, init };
|
|
1355
1729
|
this.procs.set(agentId, entry);
|
|
@@ -1361,7 +1735,7 @@ class AgentSessions {
|
|
|
1361
1735
|
this.starting.set(agentId, p);
|
|
1362
1736
|
return p;
|
|
1363
1737
|
}
|
|
1364
|
-
async open({ agentId, projectId, resumeId }) {
|
|
1738
|
+
async open({ agentId, projectId, resumeId, onRoute }) {
|
|
1365
1739
|
const { proc, init } = await this.process(agentId);
|
|
1366
1740
|
const [resumeAgent, resumeOwn] = resumeId ? splitId(resumeId) : ["", ""];
|
|
1367
1741
|
const resume = resumeOwn && (!resumeAgent || resumeAgent === agentId) ? resumeOwn : "";
|
|
@@ -1370,8 +1744,9 @@ class AgentSessions {
|
|
|
1370
1744
|
if (live)
|
|
1371
1745
|
return { sessionId: key(resume), init, raw: {}, dimuat: "hidup", routeId: live.routeId, opsi: live.opsi ?? {} };
|
|
1372
1746
|
const cwd = projectDir(projectId);
|
|
1373
|
-
|
|
1747
|
+
fs10.writeFileSync(path7.join(cwd, "AGENTS.md"), AGENTS_MD);
|
|
1374
1748
|
const routeId = crypto2.randomBytes(9).toString("base64url");
|
|
1749
|
+
onRoute?.(routeId);
|
|
1375
1750
|
const params = { cwd, mcpServers: this.o.mcpServers(cwd, projectId, routeId, this.o.agent(agentId)) };
|
|
1376
1751
|
const limit = this.o.sessionTimeoutMs ?? 90000;
|
|
1377
1752
|
let raw;
|
|
@@ -1491,6 +1866,13 @@ class AgentSessions {
|
|
|
1491
1866
|
async stopAll() {
|
|
1492
1867
|
await Promise.all([...this.procs.values()].map(({ proc }) => proc.stop()));
|
|
1493
1868
|
}
|
|
1869
|
+
async stopAgent(agentId) {
|
|
1870
|
+
const e = this.procs.get(agentId);
|
|
1871
|
+
if (!e)
|
|
1872
|
+
return false;
|
|
1873
|
+
await e.proc.stop();
|
|
1874
|
+
return true;
|
|
1875
|
+
}
|
|
1494
1876
|
queue(sessionId, update) {
|
|
1495
1877
|
const s = this.sessions.get(sessionId);
|
|
1496
1878
|
if (!s || update === undefined)
|
|
@@ -1531,100 +1913,41 @@ class AgentSessions {
|
|
|
1531
1913
|
if (method === "fs/read_text_file") {
|
|
1532
1914
|
if (!insideFolder(s.cwd, p.path))
|
|
1533
1915
|
throw new RpcError(-32602, OUTSIDE);
|
|
1534
|
-
const st =
|
|
1916
|
+
const st = fs10.statSync(path7.resolve(s.cwd, p.path), { throwIfNoEntry: false });
|
|
1535
1917
|
if (!st?.isFile())
|
|
1536
1918
|
throw new RpcError(-32602, "Not a regular file");
|
|
1537
1919
|
if (st.size > MAX_READ)
|
|
1538
1920
|
throw new RpcError(-32602, "File too large (over 10 MB)");
|
|
1539
|
-
let content =
|
|
1540
|
-
if (p.line || p.limit) {
|
|
1541
|
-
const lines = content.split(`
|
|
1542
|
-
`);
|
|
1543
|
-
const from = Math.max(0, (Number(p.line) || 1) - 1);
|
|
1544
|
-
content = lines.slice(from, p.limit ? from + Number(p.limit) : undefined).join(`
|
|
1545
|
-
`);
|
|
1546
|
-
}
|
|
1547
|
-
return { content };
|
|
1548
|
-
}
|
|
1549
|
-
if (method === "fs/write_text_file") {
|
|
1550
|
-
if (!insideFolder(s.cwd, p.path))
|
|
1551
|
-
throw new RpcError(-32602, OUTSIDE);
|
|
1552
|
-
const f =
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
return null;
|
|
1556
|
-
}
|
|
1557
|
-
throw new RpcError(-32601, `Method not found: ${method}`);
|
|
1558
|
-
}
|
|
1559
|
-
}
|
|
1560
|
-
|
|
1561
|
-
// src/agent/store.ts
|
|
1562
|
-
import fs9 from "node:fs";
|
|
1563
|
-
import path6 from "node:path";
|
|
1564
|
-
function setReady(id, ready) {
|
|
1565
|
-
const a = readInstalled().find((x) => x.id === id);
|
|
1566
|
-
if (a)
|
|
1567
|
-
writeInstalled({ ...a, ready });
|
|
1568
|
-
}
|
|
1569
|
-
var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
1570
|
-
var folder = (id) => {
|
|
1571
|
-
if (typeof id !== "string" || !AGENT_ID.test(id))
|
|
1572
|
-
throw new Error(`Invalid agent id: ${JSON.stringify(String(id)).slice(0, 60)}`);
|
|
1573
|
-
return path6.join(agentDir(), id);
|
|
1574
|
-
};
|
|
1575
|
-
function readInstalled() {
|
|
1576
|
-
const out = [];
|
|
1577
|
-
for (const id of fs9.readdirSync(agentDir())) {
|
|
1578
|
-
if (!AGENT_ID.test(id))
|
|
1579
|
-
continue;
|
|
1580
|
-
try {
|
|
1581
|
-
const a = JSON.parse(fs9.readFileSync(path6.join(folder(id), "agent.json"), "utf8"));
|
|
1582
|
-
if (a.id === id && a.launch?.cmd)
|
|
1583
|
-
out.push(a);
|
|
1584
|
-
} catch {}
|
|
1585
|
-
}
|
|
1586
|
-
return out;
|
|
1587
|
-
}
|
|
1588
|
-
function writeInstalled(a) {
|
|
1589
|
-
fs9.mkdirSync(folder(a.id), { recursive: true });
|
|
1590
|
-
const f = path6.join(folder(a.id), "agent.json");
|
|
1591
|
-
fs9.writeFileSync(`${f}.tmp`, JSON.stringify(a, null, 2));
|
|
1592
|
-
fs9.renameSync(`${f}.tmp`, f);
|
|
1593
|
-
}
|
|
1594
|
-
function removeAgent(id) {
|
|
1595
|
-
fs9.rmSync(folder(id), { recursive: true, force: true });
|
|
1596
|
-
}
|
|
1597
|
-
function agentEnv(id) {
|
|
1598
|
-
try {
|
|
1599
|
-
return JSON.parse(fs9.readFileSync(path6.join(folder(id), "env.json"), "utf8"));
|
|
1600
|
-
} catch {
|
|
1601
|
-
return {};
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
|
-
var SECRET_NAME = /KEY|TOKEN|SECRET|PASSWORD/i;
|
|
1605
|
-
function forgetAgentSecrets(id) {
|
|
1606
|
-
const gone = Object.keys(agentEnv(id)).filter((k) => SECRET_NAME.test(k));
|
|
1607
|
-
removeAgentEnv(id, gone);
|
|
1608
|
-
return gone;
|
|
1609
|
-
}
|
|
1610
|
-
function removeAgentEnv(id, names) {
|
|
1611
|
-
const env = agentEnv(id);
|
|
1612
|
-
if (!names.some((k) => (k in env)))
|
|
1613
|
-
return;
|
|
1614
|
-
for (const k of names)
|
|
1615
|
-
delete env[k];
|
|
1616
|
-
const f = path6.join(folder(id), "env.json");
|
|
1617
|
-
fs9.writeFileSync(`${f}.tmp`, JSON.stringify(env), { mode: 384 });
|
|
1618
|
-
fs9.renameSync(`${f}.tmp`, f);
|
|
1619
|
-
}
|
|
1620
|
-
function saveAgentEnv(id, env) {
|
|
1621
|
-
fs9.mkdirSync(folder(id), { recursive: true });
|
|
1622
|
-
const f = path6.join(folder(id), "env.json");
|
|
1623
|
-
fs9.writeFileSync(`${f}.tmp`, JSON.stringify({ ...agentEnv(id), ...env }), { mode: 384 });
|
|
1624
|
-
fs9.renameSync(`${f}.tmp`, f);
|
|
1921
|
+
let content = fs10.readFileSync(path7.resolve(s.cwd, p.path), "utf8");
|
|
1922
|
+
if (p.line || p.limit) {
|
|
1923
|
+
const lines = content.split(`
|
|
1924
|
+
`);
|
|
1925
|
+
const from = Math.max(0, (Number(p.line) || 1) - 1);
|
|
1926
|
+
content = lines.slice(from, p.limit ? from + Number(p.limit) : undefined).join(`
|
|
1927
|
+
`);
|
|
1928
|
+
}
|
|
1929
|
+
return { content };
|
|
1930
|
+
}
|
|
1931
|
+
if (method === "fs/write_text_file") {
|
|
1932
|
+
if (!insideFolder(s.cwd, p.path))
|
|
1933
|
+
throw new RpcError(-32602, OUTSIDE);
|
|
1934
|
+
const f = path7.resolve(s.cwd, p.path);
|
|
1935
|
+
fs10.mkdirSync(path7.dirname(f), { recursive: true });
|
|
1936
|
+
fs10.writeFileSync(f, String(p.content ?? ""));
|
|
1937
|
+
return null;
|
|
1938
|
+
}
|
|
1939
|
+
throw new RpcError(-32601, `Method not found: ${method}`);
|
|
1940
|
+
}
|
|
1625
1941
|
}
|
|
1626
1942
|
|
|
1627
1943
|
// src/agent/service.ts
|
|
1944
|
+
var hostOf = (u) => {
|
|
1945
|
+
try {
|
|
1946
|
+
return new URL(u).host;
|
|
1947
|
+
} catch {
|
|
1948
|
+
return u.slice(0, 60);
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1628
1951
|
var MAX_NEWS = 180 * 1024;
|
|
1629
1952
|
var MAX_TOOL_ARGS = 200 * 1024;
|
|
1630
1953
|
var MAX_TEXT = 48 * 1024;
|
|
@@ -1738,28 +2061,28 @@ function mcpServerFor(agent, url, key, bridge) {
|
|
|
1738
2061
|
return { name: "hypeframe", command: bridge.command, args: bridge.args, env: [...bridge.env, ...env] };
|
|
1739
2062
|
}
|
|
1740
2063
|
function historyFile(projectId, sessionId) {
|
|
1741
|
-
return
|
|
2064
|
+
return path8.join(projectDir(projectId), "riwayat", `${crypto3.createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}.jsonl`);
|
|
1742
2065
|
}
|
|
1743
2066
|
function record(file, updates) {
|
|
1744
2067
|
if (!updates.length)
|
|
1745
2068
|
return;
|
|
1746
2069
|
try {
|
|
1747
|
-
|
|
1748
|
-
|
|
2070
|
+
fs11.mkdirSync(path8.dirname(file), { recursive: true });
|
|
2071
|
+
fs11.appendFileSync(file, `${updates.map((u) => JSON.stringify(u)).join(`
|
|
1749
2072
|
`)}
|
|
1750
2073
|
`);
|
|
1751
|
-
if (
|
|
1752
|
-
const text =
|
|
2074
|
+
if (fs11.statSync(file).size > MAX_HISTORY) {
|
|
2075
|
+
const text = fs11.readFileSync(file, "utf8");
|
|
1753
2076
|
const from = text.indexOf(`
|
|
1754
2077
|
`, text.length - MAX_HISTORY / 2);
|
|
1755
|
-
|
|
2078
|
+
fs11.writeFileSync(file, from >= 0 ? text.slice(from + 1) : "");
|
|
1756
2079
|
}
|
|
1757
2080
|
} catch {}
|
|
1758
2081
|
}
|
|
1759
2082
|
function readHistory(file) {
|
|
1760
2083
|
let text = "";
|
|
1761
2084
|
try {
|
|
1762
|
-
text =
|
|
2085
|
+
text = fs11.readFileSync(file, "utf8");
|
|
1763
2086
|
} catch {
|
|
1764
2087
|
return { update: [], potong: false };
|
|
1765
2088
|
}
|
|
@@ -1814,6 +2137,13 @@ function createAgentService(o) {
|
|
|
1814
2137
|
sendUpdates(sessionId);
|
|
1815
2138
|
o.conn.news("agen", { sessionId, ...body });
|
|
1816
2139
|
};
|
|
2140
|
+
const accountRestart = new Set;
|
|
2141
|
+
const restartForAccount = (agentId) => {
|
|
2142
|
+
if (!sessions.running().includes(agentId))
|
|
2143
|
+
return Promise.resolve(false);
|
|
2144
|
+
accountRestart.add(agentId);
|
|
2145
|
+
return sessions.stopAgent(agentId);
|
|
2146
|
+
};
|
|
1817
2147
|
const sessions = new AgentSessions({
|
|
1818
2148
|
agent: (id) => readInstalled().find((a) => a.id === id),
|
|
1819
2149
|
env: (id) => agentEnv(id),
|
|
@@ -1838,7 +2168,12 @@ function createAgentService(o) {
|
|
|
1838
2168
|
setTimeout(() => permissions.has(id) && done(null), 5 * 60000).unref();
|
|
1839
2169
|
control(sessionId, { izin: { id, judul: String(req.toolCall.title ?? ""), jenis: String(req.toolCall.kind ?? ""), perintah: commandText(req), wajibTanya: info.mustAsk, opsi: req.options } });
|
|
1840
2170
|
}),
|
|
1841
|
-
onExit: (agentId, code) =>
|
|
2171
|
+
onExit: (agentId, code) => {
|
|
2172
|
+
const akun = accountRestart.delete(agentId);
|
|
2173
|
+
o.conn.news("agen", { agentId, berhenti: code, ...akun ? { akun: true } : {} });
|
|
2174
|
+
if (!akun)
|
|
2175
|
+
emit({ type: "stopped", agent: nameOf(agentId), code });
|
|
2176
|
+
},
|
|
1842
2177
|
flushMs: o.flushMs ?? 100
|
|
1843
2178
|
});
|
|
1844
2179
|
const text = (c, k) => typeof c[k] === "string" ? c[k] : "";
|
|
@@ -1856,16 +2191,29 @@ function createAgentService(o) {
|
|
|
1856
2191
|
const t0 = Date.now();
|
|
1857
2192
|
if (fresh)
|
|
1858
2193
|
emit({ type: "starting", agent: a.name });
|
|
1859
|
-
const
|
|
2194
|
+
const alat = Array.isArray(c.alat) ? c.alat : undefined;
|
|
2195
|
+
let early = "";
|
|
2196
|
+
const register = (id) => {
|
|
2197
|
+
early = id;
|
|
2198
|
+
routes.set(id, { dari: c.dari, tab, alat: alat ?? [], projectId, agentId });
|
|
2199
|
+
};
|
|
2200
|
+
let opened;
|
|
2201
|
+
try {
|
|
2202
|
+
opened = await sessions.open({ agentId, projectId, resumeId: text(c, "resume") || undefined, onRoute: register });
|
|
2203
|
+
} catch (e) {
|
|
2204
|
+
if (early)
|
|
2205
|
+
routes.delete(early);
|
|
2206
|
+
throw e;
|
|
2207
|
+
}
|
|
2208
|
+
const { sessionId, dimuat, routeId, opsi } = opened;
|
|
1860
2209
|
if (fresh)
|
|
1861
2210
|
emit({ type: "ready", agent: a.name, ms: Date.now() - t0 });
|
|
1862
2211
|
if (dimuat !== "hidup")
|
|
1863
2212
|
emit({ type: "chat", agent: a.name, resumed: dimuat === "load" });
|
|
1864
|
-
const alat = Array.isArray(c.alat) ? c.alat : undefined;
|
|
1865
2213
|
const r = routes.get(routeId);
|
|
1866
2214
|
if (!r)
|
|
1867
2215
|
routes.set(routeId, { dari: c.dari, tab, alat: alat ?? [], projectId, agentId });
|
|
1868
|
-
else {
|
|
2216
|
+
else if (routeId !== early) {
|
|
1869
2217
|
if (tab && r.tab === tab)
|
|
1870
2218
|
r.dari = c.dari;
|
|
1871
2219
|
if (alat)
|
|
@@ -1916,6 +2264,43 @@ function createAgentService(o) {
|
|
|
1916
2264
|
emit({ type: "option", agent: nameOf(sessions.agentOf(text(c, "sessionId"))), what: macam === "opsi" ? text(c, "id") : macam, value: text(c, "nilai") });
|
|
1917
2265
|
return r;
|
|
1918
2266
|
},
|
|
2267
|
+
"agen.akun": async (c) => {
|
|
2268
|
+
const agentId = text(c, "agentId");
|
|
2269
|
+
const aksi = text(c, "aksi");
|
|
2270
|
+
if (aksi === "api-model")
|
|
2271
|
+
return { model: await fetchApiModels(text(c, "url"), text(c, "kunci")) };
|
|
2272
|
+
if (!readInstalled().some((x) => x.id === agentId))
|
|
2273
|
+
throw new Error("Agen belum dipasang di mesin ini.");
|
|
2274
|
+
switch (aksi) {
|
|
2275
|
+
case "keluar": {
|
|
2276
|
+
const hasil = await logoutAgent(agentId);
|
|
2277
|
+
await restartForAccount(agentId);
|
|
2278
|
+
return { hasil };
|
|
2279
|
+
}
|
|
2280
|
+
case "masuk":
|
|
2281
|
+
return { ...startRemoteLogin(agentId) };
|
|
2282
|
+
case "status":
|
|
2283
|
+
return { ...remoteLoginState(agentId) ?? { tahap: "tidak-ada" } };
|
|
2284
|
+
case "kode":
|
|
2285
|
+
return { ...sendRemoteCode(agentId, text(c, "kode")) };
|
|
2286
|
+
case "batal":
|
|
2287
|
+
return cancelRemoteLogin(agentId), {};
|
|
2288
|
+
case "api-simpan": {
|
|
2289
|
+
if (agentId !== OPENCODE)
|
|
2290
|
+
throw new Error("API sendiri hanya untuk OpenCode.");
|
|
2291
|
+
const models = Array.isArray(c.model) ? c.model.filter((m) => typeof m === "string") : [];
|
|
2292
|
+
saveOpencodeApi({ url: text(c, "url"), key: text(c, "kunci"), models, name: text(c, "nama") || undefined });
|
|
2293
|
+
await restartForAccount(OPENCODE);
|
|
2294
|
+
return { siap: await checkReady(OPENCODE) };
|
|
2295
|
+
}
|
|
2296
|
+
case "api-hapus":
|
|
2297
|
+
removeOpencodeApi();
|
|
2298
|
+
await restartForAccount(OPENCODE);
|
|
2299
|
+
return {};
|
|
2300
|
+
default:
|
|
2301
|
+
throw new Error("Pilihan tidak dikenal.");
|
|
2302
|
+
}
|
|
2303
|
+
},
|
|
1919
2304
|
"agen.riwayat": async (c) => {
|
|
1920
2305
|
try {
|
|
1921
2306
|
return readHistory(historyFile(text(c, "projectId"), text(c, "sessionId")));
|
|
@@ -1930,17 +2315,17 @@ function createAgentService(o) {
|
|
|
1930
2315
|
const folder = projectDir(projectId);
|
|
1931
2316
|
if (!p || !insideFolder(folder, p))
|
|
1932
2317
|
return fail(`Only files inside the HypeFrame project folder (${folder}) can be added.`);
|
|
1933
|
-
const file =
|
|
1934
|
-
const st =
|
|
2318
|
+
const file = path8.resolve(folder, p);
|
|
2319
|
+
const st = fs11.statSync(file, { throwIfNoEntry: false });
|
|
1935
2320
|
if (!st?.isFile())
|
|
1936
2321
|
return fail(`${p} is not a file in the project folder.`);
|
|
1937
|
-
const nama =
|
|
1938
|
-
const mime = MEDIA[
|
|
2322
|
+
const nama = path8.basename(file).slice(0, 120);
|
|
2323
|
+
const mime = MEDIA[path8.extname(file).slice(1).toLowerCase()];
|
|
1939
2324
|
if (!mime)
|
|
1940
2325
|
return fail(`${nama}: only images, audio, video, fonts and Lottie/JSON files can be added to a HypeFrame project.`);
|
|
1941
2326
|
if (st.size > MAX_FILE2)
|
|
1942
2327
|
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.`);
|
|
1943
|
-
const data =
|
|
2328
|
+
const data = fs11.readFileSync(file).toString("base64");
|
|
1944
2329
|
const n = Math.max(1, Math.ceil(data.length / PIECE));
|
|
1945
2330
|
const id = crypto3.randomBytes(8).toString("hex");
|
|
1946
2331
|
let last = {};
|
|
@@ -2013,24 +2398,46 @@ function createAgentService(o) {
|
|
|
2013
2398
|
}
|
|
2014
2399
|
}
|
|
2015
2400
|
function capabilities() {
|
|
2016
|
-
|
|
2401
|
+
const api = opencodeApi();
|
|
2402
|
+
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, ...a.id === OPENCODE && api ? { api: hostOf(api.url) } : {} }));
|
|
2403
|
+
}
|
|
2404
|
+
const stamps = new Map;
|
|
2405
|
+
const stampOf = (id) => [path8.join(agentDir(), id, "agent.json"), path8.join(agentDir(), id, "env.json"), ...id === OPENCODE ? [path8.join(dataDir(), "opencode.json")] : []].map((f) => fs11.statSync(f, { throwIfNoEntry: false })?.mtimeMs ?? 0).join(":");
|
|
2406
|
+
function checkAccounts() {
|
|
2407
|
+
const running = sessions.running();
|
|
2408
|
+
const restarted = [];
|
|
2409
|
+
for (const id of running) {
|
|
2410
|
+
const now = stampOf(id);
|
|
2411
|
+
const before = stamps.get(id);
|
|
2412
|
+
stamps.set(id, now);
|
|
2413
|
+
if (before !== undefined && before !== now) {
|
|
2414
|
+
restartForAccount(id);
|
|
2415
|
+
stamps.delete(id);
|
|
2416
|
+
restarted.push(nameOf(id));
|
|
2417
|
+
emit({ type: "account", agent: nameOf(id) });
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
for (const id of [...stamps.keys()])
|
|
2421
|
+
if (!running.includes(id))
|
|
2422
|
+
stamps.delete(id);
|
|
2423
|
+
return restarted;
|
|
2017
2424
|
}
|
|
2018
2425
|
function activity() {
|
|
2019
2426
|
return { chats: sessions.count(), working: sessions.working(), agents: sessions.running().map((id) => nameOf(id)) };
|
|
2020
2427
|
}
|
|
2021
|
-
return { work, route, capabilities, activity, key, stop: () => (stopping = true, clearInterval(ticker), sessions.stopAll()) };
|
|
2428
|
+
return { work, route, capabilities, checkAccounts, activity, key, stop: () => (stopping = true, clearInterval(ticker), sessions.stopAll()) };
|
|
2022
2429
|
}
|
|
2023
2430
|
|
|
2024
2431
|
// src/agent/mcp-bridge.ts
|
|
2025
|
-
import
|
|
2026
|
-
import
|
|
2432
|
+
import fs13 from "node:fs";
|
|
2433
|
+
import path10 from "node:path";
|
|
2027
2434
|
import readline2 from "node:readline";
|
|
2028
2435
|
|
|
2029
2436
|
// src/util/runtime.ts
|
|
2030
|
-
import
|
|
2031
|
-
import
|
|
2437
|
+
import fs12 from "node:fs";
|
|
2438
|
+
import path9 from "node:path";
|
|
2032
2439
|
function isStandalone() {
|
|
2033
|
-
return
|
|
2440
|
+
return path9.basename(process.execPath).toLowerCase().startsWith("hypeframe");
|
|
2034
2441
|
}
|
|
2035
2442
|
function runtimeLabel() {
|
|
2036
2443
|
const bun = process.versions.bun;
|
|
@@ -2040,7 +2447,7 @@ function launchCommand() {
|
|
|
2040
2447
|
if (isStandalone())
|
|
2041
2448
|
return [process.execPath];
|
|
2042
2449
|
try {
|
|
2043
|
-
const script =
|
|
2450
|
+
const script = fs12.realpathSync(process.argv[1] || "");
|
|
2044
2451
|
return /[\\/]_npx[\\/]/.test(script) ? null : [process.execPath, script];
|
|
2045
2452
|
} catch {
|
|
2046
2453
|
return null;
|
|
@@ -2076,13 +2483,13 @@ rl.on('line', (line) => {
|
|
|
2076
2483
|
rl.on('close', () => Promise.all(busy).then(() => process.exit(0)));
|
|
2077
2484
|
`;
|
|
2078
2485
|
function bridgeLaunch() {
|
|
2079
|
-
const file =
|
|
2486
|
+
const file = path10.join(agentDir(), "mcp-bridge.mjs");
|
|
2080
2487
|
let now = "";
|
|
2081
2488
|
try {
|
|
2082
|
-
now =
|
|
2489
|
+
now = fs13.readFileSync(file, "utf8");
|
|
2083
2490
|
} catch {}
|
|
2084
2491
|
if (now !== BRIDGE_SOURCE)
|
|
2085
|
-
|
|
2492
|
+
fs13.writeFileSync(file, BRIDGE_SOURCE);
|
|
2086
2493
|
return { command: process.execPath, args: [file], env: isStandalone() ? [{ name: "BUN_BE_BUN", value: "1" }] : [] };
|
|
2087
2494
|
}
|
|
2088
2495
|
async function runMcpBridge() {
|
|
@@ -2128,7 +2535,7 @@ async function runMcpBridge() {
|
|
|
2128
2535
|
}
|
|
2129
2536
|
|
|
2130
2537
|
// src/config/lock.ts
|
|
2131
|
-
import
|
|
2538
|
+
import fs14 from "node:fs";
|
|
2132
2539
|
class AlreadyRunning extends Error {
|
|
2133
2540
|
code = "SUDAH_JALAN";
|
|
2134
2541
|
}
|
|
@@ -2142,7 +2549,7 @@ var alive = (pid) => {
|
|
|
2142
2549
|
};
|
|
2143
2550
|
function runningPid() {
|
|
2144
2551
|
try {
|
|
2145
|
-
const pid = Number(
|
|
2552
|
+
const pid = Number(fs14.readFileSync(lockFile(), "utf8"));
|
|
2146
2553
|
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
|
|
2147
2554
|
} catch {
|
|
2148
2555
|
return null;
|
|
@@ -2152,13 +2559,13 @@ function singleInstance() {
|
|
|
2152
2559
|
const f = lockFile();
|
|
2153
2560
|
for (let attempt = 0;attempt < 2; attempt++) {
|
|
2154
2561
|
try {
|
|
2155
|
-
const fd =
|
|
2156
|
-
|
|
2157
|
-
|
|
2562
|
+
const fd = fs14.openSync(f, "wx");
|
|
2563
|
+
fs14.writeSync(fd, String(process.pid));
|
|
2564
|
+
fs14.closeSync(fd);
|
|
2158
2565
|
const release = () => {
|
|
2159
2566
|
try {
|
|
2160
|
-
if (
|
|
2161
|
-
|
|
2567
|
+
if (fs14.readFileSync(f, "utf8") === String(process.pid))
|
|
2568
|
+
fs14.rmSync(f, { force: true });
|
|
2162
2569
|
} catch {}
|
|
2163
2570
|
process.off("exit", release);
|
|
2164
2571
|
};
|
|
@@ -2167,10 +2574,10 @@ function singleInstance() {
|
|
|
2167
2574
|
} catch (e) {
|
|
2168
2575
|
if (e.code !== "EEXIST")
|
|
2169
2576
|
throw e;
|
|
2170
|
-
const pid = Number(
|
|
2577
|
+
const pid = Number(fs14.readFileSync(f, "utf8"));
|
|
2171
2578
|
if (Number.isInteger(pid) && pid > 0 && alive(pid))
|
|
2172
2579
|
throw new AlreadyRunning("engine already running");
|
|
2173
|
-
|
|
2580
|
+
fs14.rmSync(f, { force: true });
|
|
2174
2581
|
}
|
|
2175
2582
|
}
|
|
2176
2583
|
throw new AlreadyRunning("engine already running");
|
|
@@ -2406,44 +2813,55 @@ async function pair(o) {
|
|
|
2406
2813
|
}
|
|
2407
2814
|
|
|
2408
2815
|
// src/render/chrome.ts
|
|
2409
|
-
import
|
|
2816
|
+
import fs15 from "node:fs";
|
|
2410
2817
|
import http from "node:http";
|
|
2411
|
-
import
|
|
2818
|
+
import path11 from "node:path";
|
|
2412
2819
|
import { Browser, detectBrowserPlatform, getInstalledBrowsers, install, resolveBuildId } from "@puppeteer/browsers";
|
|
2413
2820
|
import puppeteer from "puppeteer-core";
|
|
2414
2821
|
var ANDROID_ARGS = ["--no-sandbox", "--disable-dev-shm-usage"];
|
|
2415
|
-
var ANDROID_FALLBACKS = [
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2822
|
+
var ANDROID_FALLBACKS = [
|
|
2823
|
+
{ args: [], pipe: false },
|
|
2824
|
+
{ args: [], pipe: true },
|
|
2825
|
+
{ args: ["--enable-features=NetworkServiceInProcess2"], pipe: true },
|
|
2826
|
+
{ args: ["--single-process", "--no-zygote"], pipe: true },
|
|
2827
|
+
{ args: ["--enable-features=NetworkServiceInProcess2"], pipe: false },
|
|
2828
|
+
{ args: ["--single-process", "--no-zygote"], pipe: false }
|
|
2829
|
+
];
|
|
2830
|
+
var flagsFile = () => path11.join(dataDir(), "chrome-flags.json");
|
|
2831
|
+
var sameCara = (a, b) => a.pipe === b.pipe && a.args.length === b.args.length && a.args.every((x, i) => x === b.args[i]);
|
|
2832
|
+
function savedCara() {
|
|
2419
2833
|
try {
|
|
2420
|
-
const
|
|
2421
|
-
|
|
2834
|
+
const j = JSON.parse(fs15.readFileSync(flagsFile(), "utf8"));
|
|
2835
|
+
const c = { args: Array.isArray(j.args) ? j.args.map(String) : [], pipe: j.pipe === true };
|
|
2836
|
+
return ANDROID_FALLBACKS.some((f) => sameCara(f, c)) ? c : { args: [], pipe: false };
|
|
2422
2837
|
} catch {
|
|
2423
|
-
return [];
|
|
2838
|
+
return { args: [], pipe: false };
|
|
2424
2839
|
}
|
|
2425
2840
|
}
|
|
2426
|
-
function
|
|
2841
|
+
function saveCara(c) {
|
|
2427
2842
|
try {
|
|
2428
|
-
if (
|
|
2429
|
-
|
|
2843
|
+
if (c.args.length || c.pipe)
|
|
2844
|
+
fs15.writeFileSync(flagsFile(), JSON.stringify(c));
|
|
2430
2845
|
else
|
|
2431
|
-
|
|
2846
|
+
fs15.rmSync(flagsFile(), { force: true });
|
|
2432
2847
|
} catch {}
|
|
2433
2848
|
}
|
|
2434
2849
|
function chromePlatformArgs(android = isAndroid()) {
|
|
2435
|
-
return android ? [...ANDROID_ARGS, ...
|
|
2850
|
+
return android ? [...ANDROID_ARGS, ...savedCara().args] : [];
|
|
2851
|
+
}
|
|
2852
|
+
function chromePipe(android = isAndroid()) {
|
|
2853
|
+
return android && savedCara().pipe;
|
|
2436
2854
|
}
|
|
2437
2855
|
async function probeChrome(attempt, android = isAndroid()) {
|
|
2438
2856
|
if (!android)
|
|
2439
|
-
return attempt([]);
|
|
2440
|
-
const saved =
|
|
2857
|
+
return attempt({ args: [], pipe: false });
|
|
2858
|
+
const saved = savedCara();
|
|
2441
2859
|
let first;
|
|
2442
|
-
for (const
|
|
2860
|
+
for (const cara of [saved, ...ANDROID_FALLBACKS.filter((f) => !sameCara(f, saved))]) {
|
|
2443
2861
|
try {
|
|
2444
|
-
const r = await attempt([...
|
|
2445
|
-
if (!
|
|
2446
|
-
|
|
2862
|
+
const r = await attempt({ args: [...cara.args], pipe: cara.pipe });
|
|
2863
|
+
if (!sameCara(cara, saved))
|
|
2864
|
+
saveCara(cara);
|
|
2447
2865
|
return r;
|
|
2448
2866
|
} catch (e) {
|
|
2449
2867
|
first ??= e;
|
|
@@ -2458,7 +2876,7 @@ function chromeLogHint(log) {
|
|
|
2458
2876
|
function candidates() {
|
|
2459
2877
|
const e = process.env;
|
|
2460
2878
|
if (process.platform === "win32") {
|
|
2461
|
-
return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [
|
|
2879
|
+
return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [path11.join(d, "Google", "Chrome", "Application", "chrome.exe"), path11.join(d, "Microsoft", "Edge", "Application", "msedge.exe")]);
|
|
2462
2880
|
}
|
|
2463
2881
|
if (process.platform === "darwin") {
|
|
2464
2882
|
return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
|
|
@@ -2468,15 +2886,15 @@ function candidates() {
|
|
|
2468
2886
|
function findChrome(android = isAndroid()) {
|
|
2469
2887
|
const forced = process.env.HYPEFRAME_CHROME;
|
|
2470
2888
|
if (forced)
|
|
2471
|
-
return
|
|
2889
|
+
return fs15.existsSync(forced) ? forced : null;
|
|
2472
2890
|
if (android && linuxChromiumReady())
|
|
2473
2891
|
return chromiumWrapper();
|
|
2474
|
-
return candidates().find((p) =>
|
|
2892
|
+
return candidates().find((p) => fs15.existsSync(p)) || null;
|
|
2475
2893
|
}
|
|
2476
2894
|
async function cachedChrome(cacheDir) {
|
|
2477
2895
|
try {
|
|
2478
|
-
const all = await getInstalledBrowsers({ cacheDir:
|
|
2479
|
-
return all.find((b) => b.browser === Browser.CHROME &&
|
|
2896
|
+
const all = await getInstalledBrowsers({ cacheDir: path11.join(cacheDir, "chrome") });
|
|
2897
|
+
return all.find((b) => b.browser === Browser.CHROME && fs15.existsSync(b.executablePath))?.executablePath ?? null;
|
|
2480
2898
|
} catch {
|
|
2481
2899
|
return null;
|
|
2482
2900
|
}
|
|
@@ -2495,7 +2913,7 @@ async function prepareChrome(cacheDir, progress = () => {
|
|
|
2495
2913
|
const platform = detectBrowserPlatform();
|
|
2496
2914
|
if (!platform)
|
|
2497
2915
|
throw new Error("Sistem ini belum didukung untuk render (Chrome tidak tersedia).");
|
|
2498
|
-
const dir =
|
|
2916
|
+
const dir = path11.join(cacheDir, "chrome");
|
|
2499
2917
|
const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
|
|
2500
2918
|
progress(0, `Chrome ${buildId}`);
|
|
2501
2919
|
const r = await install({
|
|
@@ -2524,14 +2942,14 @@ var TRY_ENCODER = `async (c) => {
|
|
|
2524
2942
|
});
|
|
2525
2943
|
}`;
|
|
2526
2944
|
async function checkChrome(chrome, { gpu = false, android = isAndroid() } = {}) {
|
|
2527
|
-
return probeChrome(async (
|
|
2945
|
+
return probeChrome(async (cara) => ({ ...await checkOnce(chrome, gpu, android ? [...ANDROID_ARGS, ...cara.args] : [], cara.pipe), extra: [...cara.args, ...cara.pipe ? ["pipe"] : []] }), android);
|
|
2528
2946
|
}
|
|
2529
|
-
async function checkOnce(chrome, gpu, platformArgs) {
|
|
2947
|
+
async function checkOnce(chrome, gpu, platformArgs, pipe = false) {
|
|
2530
2948
|
const srv = http.createServer((_q, r) => (r.writeHead(200, { "content-type": "text/html" }), r.end("<!doctype html><title>check</title>")));
|
|
2531
2949
|
await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
|
|
2532
2950
|
let b;
|
|
2533
2951
|
try {
|
|
2534
|
-
b = await puppeteer.launch({ executablePath: chrome, headless: true, protocolTimeout: 60000, args: ["--no-first-run", "--disable-extensions", ...gpu ? [] : softwareGpuArgs, ...platformArgs] });
|
|
2952
|
+
b = await puppeteer.launch({ executablePath: chrome, headless: true, pipe, protocolTimeout: 60000, args: ["--no-first-run", "--disable-extensions", ...gpu ? [] : softwareGpuArgs, ...platformArgs] });
|
|
2535
2953
|
} catch (e) {
|
|
2536
2954
|
srv.close();
|
|
2537
2955
|
throw e;
|
|
@@ -2560,9 +2978,9 @@ async function checkOnce(chrome, gpu, platformArgs) {
|
|
|
2560
2978
|
|
|
2561
2979
|
// src/render/ffmpeg.ts
|
|
2562
2980
|
import crypto5 from "node:crypto";
|
|
2563
|
-
import
|
|
2981
|
+
import fs16 from "node:fs";
|
|
2564
2982
|
import fsp from "node:fs/promises";
|
|
2565
|
-
import
|
|
2983
|
+
import path12 from "node:path";
|
|
2566
2984
|
import { pipeline } from "node:stream/promises";
|
|
2567
2985
|
import { Readable } from "node:stream";
|
|
2568
2986
|
import zlib from "node:zlib";
|
|
@@ -2576,22 +2994,22 @@ var FFMPEG_PINNED = {
|
|
|
2576
2994
|
"darwin-arm64": { sha256: "6be74d6f449889c2e87a75873894f8520cad56c08ac76f2a628d85b0519daaca", size: 19253088 }
|
|
2577
2995
|
};
|
|
2578
2996
|
var exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
|
|
2579
|
-
var cached2 = (cacheDir) =>
|
|
2997
|
+
var cached2 = (cacheDir) => path12.join(cacheDir, "ffmpeg", FFMPEG_RELEASE, exe);
|
|
2580
2998
|
var thisPlatform = () => `${process.platform}-${process.arch}`;
|
|
2581
2999
|
async function findFfmpeg(cacheDir, key = thisPlatform()) {
|
|
2582
3000
|
const forced = process.env.HYPEFRAME_FFMPEG;
|
|
2583
3001
|
if (forced)
|
|
2584
|
-
return
|
|
3002
|
+
return fs16.existsSync(forced) ? forced : null;
|
|
2585
3003
|
if (!FFMPEG_PINNED[key])
|
|
2586
3004
|
return onPath("ffmpeg");
|
|
2587
3005
|
try {
|
|
2588
3006
|
const mod = await import("ffmpeg-static");
|
|
2589
3007
|
const p = typeof mod.default === "string" ? mod.default : null;
|
|
2590
|
-
if (p &&
|
|
3008
|
+
if (p && fs16.existsSync(p))
|
|
2591
3009
|
return p;
|
|
2592
3010
|
} catch {}
|
|
2593
3011
|
const c = cached2(cacheDir);
|
|
2594
|
-
return
|
|
3012
|
+
return fs16.existsSync(c) ? c : null;
|
|
2595
3013
|
}
|
|
2596
3014
|
async function downloadVerified(url, sha256, dest, progress = () => {
|
|
2597
3015
|
return;
|
|
@@ -2600,7 +3018,7 @@ async function downloadVerified(url, sha256, dest, progress = () => {
|
|
|
2600
3018
|
if (!r.ok || !r.body)
|
|
2601
3019
|
throw new Error(`download ${r.status}`);
|
|
2602
3020
|
const total = Number(r.headers.get("content-length")) || 0;
|
|
2603
|
-
await fsp.mkdir(
|
|
3021
|
+
await fsp.mkdir(path12.dirname(dest), { recursive: true });
|
|
2604
3022
|
const tmp = `${dest}.download`;
|
|
2605
3023
|
const hash = crypto5.createHash("sha256");
|
|
2606
3024
|
let got = 0;
|
|
@@ -2612,13 +3030,13 @@ async function downloadVerified(url, sha256, dest, progress = () => {
|
|
|
2612
3030
|
if (pct - last >= 10)
|
|
2613
3031
|
last = pct, progress(pct);
|
|
2614
3032
|
});
|
|
2615
|
-
await pipeline(body,
|
|
3033
|
+
await pipeline(body, fs16.createWriteStream(tmp));
|
|
2616
3034
|
if (hash.digest("hex") !== sha256) {
|
|
2617
3035
|
await fsp.rm(tmp, { force: true });
|
|
2618
3036
|
throw new Error("ffmpeg: sidik unduhan tidak cocok, berkas ditolak.");
|
|
2619
3037
|
}
|
|
2620
3038
|
if (gunzip) {
|
|
2621
|
-
await pipeline(
|
|
3039
|
+
await pipeline(fs16.createReadStream(tmp), zlib.createGunzip(), fs16.createWriteStream(`${tmp}.raw`));
|
|
2622
3040
|
await fsp.rm(tmp, { force: true });
|
|
2623
3041
|
await fsp.rename(`${tmp}.raw`, dest);
|
|
2624
3042
|
} else
|
|
@@ -2641,16 +3059,16 @@ async function prepareFfmpeg(cacheDir, progress = () => {
|
|
|
2641
3059
|
}
|
|
2642
3060
|
|
|
2643
3061
|
// src/render/job.ts
|
|
2644
|
-
import { spawn as
|
|
3062
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
2645
3063
|
import crypto6 from "node:crypto";
|
|
2646
|
-
import
|
|
3064
|
+
import fs17 from "node:fs";
|
|
2647
3065
|
import fsp2 from "node:fs/promises";
|
|
2648
|
-
import
|
|
3066
|
+
import path13 from "node:path";
|
|
2649
3067
|
import puppeteer2 from "puppeteer-core";
|
|
2650
3068
|
var LIMIT_SECONDS = 1800;
|
|
2651
3069
|
function run(cmd, args, limitSeconds = 600) {
|
|
2652
3070
|
return new Promise((ok, fail) => {
|
|
2653
|
-
const p =
|
|
3071
|
+
const p = spawn3(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
2654
3072
|
let err = "";
|
|
2655
3073
|
p.stderr.on("data", (d) => err = (err + d).slice(-2000));
|
|
2656
3074
|
const timer = setTimeout(() => p.kill("SIGKILL"), limitSeconds * 1000);
|
|
@@ -2662,7 +3080,7 @@ function run(cmd, args, limitSeconds = 600) {
|
|
|
2662
3080
|
function saveBody(req, to, max) {
|
|
2663
3081
|
return new Promise((ok, fail) => {
|
|
2664
3082
|
let n = 0;
|
|
2665
|
-
const out =
|
|
3083
|
+
const out = fs17.createWriteStream(to);
|
|
2666
3084
|
req.on("data", (d) => {
|
|
2667
3085
|
n += d.length;
|
|
2668
3086
|
if (n > max)
|
|
@@ -2704,12 +3122,13 @@ function createJobRunner(o) {
|
|
|
2704
3122
|
let browser;
|
|
2705
3123
|
try {
|
|
2706
3124
|
progress(0, "Menyiapkan");
|
|
2707
|
-
const profile =
|
|
2708
|
-
await fsp2.mkdir(
|
|
2709
|
-
await fsp2.writeFile(
|
|
3125
|
+
const profile = path13.join(task.dir, "profil");
|
|
3126
|
+
await fsp2.mkdir(path13.join(profile, "Default"), { recursive: true });
|
|
3127
|
+
await fsp2.writeFile(path13.join(profile, "Default", "Preferences"), JSON.stringify({ webkit: { webprefs: { fonts: { standard: { Zyyy: "Roboto" }, sansserif: { Zyyy: "Roboto" }, serif: { Zyyy: "Noto Serif" } } } } }));
|
|
2710
3128
|
browser = await puppeteer2.launch({
|
|
2711
3129
|
executablePath: chrome,
|
|
2712
3130
|
headless: true,
|
|
3131
|
+
pipe: chromePipe(),
|
|
2713
3132
|
userDataDir: profile,
|
|
2714
3133
|
args: [
|
|
2715
3134
|
"--no-first-run",
|
|
@@ -2737,9 +3156,9 @@ function createJobRunner(o) {
|
|
|
2737
3156
|
if (result.error)
|
|
2738
3157
|
throw new Error(result.error);
|
|
2739
3158
|
progress(99, clip ? "Menyelesaikan klip" : "Menyelesaikan video");
|
|
2740
|
-
const raw =
|
|
3159
|
+
const raw = path13.join(task.dir, "mentah.mp4");
|
|
2741
3160
|
const webm = clip && task.transparent;
|
|
2742
|
-
const file =
|
|
3161
|
+
const file = path13.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
|
|
2743
3162
|
if (clip)
|
|
2744
3163
|
await fsp2.rename(raw, file);
|
|
2745
3164
|
else
|
|
@@ -2766,11 +3185,11 @@ function createJobRunner(o) {
|
|
|
2766
3185
|
return res.writeHead(403), res.end(), true;
|
|
2767
3186
|
const pkg = r.task.packageDir;
|
|
2768
3187
|
if (m[2] === "proyek.json" || m[2] === "klip.json" || m[3]) {
|
|
2769
|
-
const f = m[3] ?
|
|
2770
|
-
if (!
|
|
3188
|
+
const f = m[3] ? path13.join(pkg, "aset", m[3]) : path13.join(pkg, m[2]);
|
|
3189
|
+
if (!fs17.existsSync(f))
|
|
2771
3190
|
return res.writeHead(404), res.end(), true;
|
|
2772
3191
|
res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp2.stat(f)).size });
|
|
2773
|
-
|
|
3192
|
+
fs17.createReadStream(f).pipe(res);
|
|
2774
3193
|
return true;
|
|
2775
3194
|
}
|
|
2776
3195
|
if (m[2] === "kemajuan") {
|
|
@@ -2787,7 +3206,7 @@ function createJobRunner(o) {
|
|
|
2787
3206
|
r.finish({ error: String(b.pesan || "Render gagal.").slice(0, 300) });
|
|
2788
3207
|
return res.writeHead(204), res.end(), true;
|
|
2789
3208
|
}
|
|
2790
|
-
await saveBody(req,
|
|
3209
|
+
await saveBody(req, path13.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
|
|
2791
3210
|
r.finish({ audio: String(req.headers["x-kodek-audio"] || "") });
|
|
2792
3211
|
res.writeHead(204);
|
|
2793
3212
|
res.end();
|
|
@@ -2797,9 +3216,9 @@ function createJobRunner(o) {
|
|
|
2797
3216
|
}
|
|
2798
3217
|
|
|
2799
3218
|
// src/render/page.ts
|
|
2800
|
-
import
|
|
3219
|
+
import fs18 from "node:fs";
|
|
2801
3220
|
import fsp3 from "node:fs/promises";
|
|
2802
|
-
import
|
|
3221
|
+
import path14 from "node:path";
|
|
2803
3222
|
var TYPES = {
|
|
2804
3223
|
".html": "text/html; charset=utf-8",
|
|
2805
3224
|
".js": "text/javascript",
|
|
@@ -2820,13 +3239,13 @@ var SAFE_PATH = /^[\w@.+-]+(?:\/[\w@.+-]+)*$/;
|
|
|
2820
3239
|
var VERSION_ID = /^[0-9a-f]{12}$/;
|
|
2821
3240
|
function createPage({ web, cacheDir }) {
|
|
2822
3241
|
const base = `${String(web || "").replace(/\/+$/, "")}/render/`;
|
|
2823
|
-
const root =
|
|
3242
|
+
const root = path14.join(cacheDir, "halaman");
|
|
2824
3243
|
let version = null;
|
|
2825
|
-
const versionDir = () =>
|
|
3244
|
+
const versionDir = () => path14.join(root, version);
|
|
2826
3245
|
const pending = new Map;
|
|
2827
3246
|
async function download(rel) {
|
|
2828
|
-
const target =
|
|
2829
|
-
if (
|
|
3247
|
+
const target = path14.join(versionDir(), rel);
|
|
3248
|
+
if (fs18.existsSync(target))
|
|
2830
3249
|
return target;
|
|
2831
3250
|
if (!pending.has(rel)) {
|
|
2832
3251
|
pending.set(rel, (async () => {
|
|
@@ -2834,7 +3253,7 @@ function createPage({ web, cacheDir }) {
|
|
|
2834
3253
|
if (!r.ok)
|
|
2835
3254
|
throw Object.assign(new Error(`halaman ${rel}: ${r.status}`), { status: r.status });
|
|
2836
3255
|
const body = Buffer.from(await r.arrayBuffer());
|
|
2837
|
-
await fsp3.mkdir(
|
|
3256
|
+
await fsp3.mkdir(path14.dirname(target), { recursive: true });
|
|
2838
3257
|
await fsp3.writeFile(`${target}.tmp`, body);
|
|
2839
3258
|
await fsp3.rename(`${target}.tmp`, target);
|
|
2840
3259
|
return target;
|
|
@@ -2858,10 +3277,10 @@ function createPage({ web, cacheDir }) {
|
|
|
2858
3277
|
await download(f);
|
|
2859
3278
|
if (old !== version) {
|
|
2860
3279
|
const all = (await fsp3.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
|
|
2861
|
-
const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(
|
|
3280
|
+
const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp3.stat(path14.join(root, d))).mtimeMs })));
|
|
2862
3281
|
for (const { d } of dated.sort((a, b) => b.t - a.t).slice(2))
|
|
2863
3282
|
if (d !== version)
|
|
2864
|
-
await fsp3.rm(
|
|
3283
|
+
await fsp3.rm(path14.join(root, d), { recursive: true, force: true });
|
|
2865
3284
|
}
|
|
2866
3285
|
return { version };
|
|
2867
3286
|
}
|
|
@@ -2878,8 +3297,8 @@ function createPage({ web, cacheDir }) {
|
|
|
2878
3297
|
return res.writeHead(404), res.end(), true;
|
|
2879
3298
|
try {
|
|
2880
3299
|
const f = await download(rel);
|
|
2881
|
-
res.writeHead(200, { "content-type": TYPES[
|
|
2882
|
-
|
|
3300
|
+
res.writeHead(200, { "content-type": TYPES[path14.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
|
|
3301
|
+
fs18.createReadStream(f).pipe(res);
|
|
2883
3302
|
} catch (e) {
|
|
2884
3303
|
res.writeHead(e.status === 404 ? 404 : 502);
|
|
2885
3304
|
res.end();
|
|
@@ -3014,10 +3433,10 @@ async function runRelayJob(j, o) {
|
|
|
3014
3433
|
|
|
3015
3434
|
// src/render/service.ts
|
|
3016
3435
|
import crypto8 from "node:crypto";
|
|
3017
|
-
import
|
|
3436
|
+
import fs19 from "node:fs";
|
|
3018
3437
|
import fsp4 from "node:fs/promises";
|
|
3019
3438
|
import http2 from "node:http";
|
|
3020
|
-
import
|
|
3439
|
+
import path15 from "node:path";
|
|
3021
3440
|
import yauzl from "yauzl";
|
|
3022
3441
|
var ACTIVE = new Set(["unggah", "antre", "jalan"]);
|
|
3023
3442
|
var safeEqual = (a, b) => a.length === b.length && crypto8.timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
@@ -3044,14 +3463,14 @@ function extractZip(f, to) {
|
|
|
3044
3463
|
zip.on("entry", (en) => {
|
|
3045
3464
|
if (en.fileName.endsWith("/"))
|
|
3046
3465
|
return zip.readEntry();
|
|
3047
|
-
const target =
|
|
3048
|
-
if (!target.startsWith(to +
|
|
3466
|
+
const target = path15.join(to, en.fileName);
|
|
3467
|
+
if (!target.startsWith(to + path15.sep))
|
|
3049
3468
|
return fail(new Error(EngineError.BadPackage));
|
|
3050
|
-
|
|
3469
|
+
fs19.mkdirSync(path15.dirname(target), { recursive: true });
|
|
3051
3470
|
zip.openReadStream(en, (e2, s) => {
|
|
3052
3471
|
if (e2 || !s)
|
|
3053
3472
|
return fail(e2 ?? new Error("zip"));
|
|
3054
|
-
const out =
|
|
3473
|
+
const out = fs19.createWriteStream(target);
|
|
3055
3474
|
s.pipe(out);
|
|
3056
3475
|
out.on("finish", () => zip.readEntry());
|
|
3057
3476
|
out.on("error", fail);
|
|
@@ -3066,13 +3485,13 @@ function extractZip(f, to) {
|
|
|
3066
3485
|
function saveBody2(req, to, max) {
|
|
3067
3486
|
return new Promise((ok, fail) => {
|
|
3068
3487
|
let n = 0;
|
|
3069
|
-
const out =
|
|
3488
|
+
const out = fs19.createWriteStream(to);
|
|
3070
3489
|
req.on("data", (d) => {
|
|
3071
3490
|
n += d.length;
|
|
3072
3491
|
if (n > max) {
|
|
3073
3492
|
req.destroy();
|
|
3074
3493
|
out.destroy();
|
|
3075
|
-
|
|
3494
|
+
fs19.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
|
|
3076
3495
|
}
|
|
3077
3496
|
});
|
|
3078
3497
|
req.pipe(out);
|
|
@@ -3101,7 +3520,7 @@ async function createRenderService(o) {
|
|
|
3101
3520
|
} } = o;
|
|
3102
3521
|
const origins = new Set([].concat(o.origin || []));
|
|
3103
3522
|
const sign = (kind, body) => crypto8.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
|
|
3104
|
-
const dir = (job) =>
|
|
3523
|
+
const dir = (job) => path15.join(folder, job);
|
|
3105
3524
|
await fsp4.mkdir(folder, { recursive: true });
|
|
3106
3525
|
function readTicket(req) {
|
|
3107
3526
|
const tk = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
|
|
@@ -3123,7 +3542,7 @@ async function createRenderService(o) {
|
|
|
3123
3542
|
const jobs = new Map;
|
|
3124
3543
|
const queue = [];
|
|
3125
3544
|
let current = null;
|
|
3126
|
-
const persist = (t) => fsp4.writeFile(
|
|
3545
|
+
const persist = (t) => fsp4.writeFile(path15.join(dir(t.job), "status.json"), JSON.stringify(t)).catch(() => {
|
|
3127
3546
|
return;
|
|
3128
3547
|
});
|
|
3129
3548
|
const update = (t, patch) => (Object.assign(t, patch, { diperbarui: Date.now() }), void persist(t));
|
|
@@ -3142,19 +3561,19 @@ async function createRenderService(o) {
|
|
|
3142
3561
|
});
|
|
3143
3562
|
async function clearFiles(t, all = false) {
|
|
3144
3563
|
for (const n of all ? ["."] : ["paket", "paket.zip", "profil", "mentah.mp4", "mentah.webm"])
|
|
3145
|
-
await fsp4.rm(
|
|
3564
|
+
await fsp4.rm(path15.join(dir(t.job), n), { recursive: true, force: true }).catch(() => {
|
|
3146
3565
|
return;
|
|
3147
3566
|
});
|
|
3148
3567
|
if (!all) {
|
|
3149
3568
|
for (const f of await fsp4.readdir(dir(t.job)).catch(() => []))
|
|
3150
3569
|
if (/^p\d+$/.test(f))
|
|
3151
|
-
await fsp4.rm(
|
|
3570
|
+
await fsp4.rm(path15.join(dir(t.job), f), { force: true });
|
|
3152
3571
|
}
|
|
3153
3572
|
}
|
|
3154
3573
|
async function openPackage(t) {
|
|
3155
3574
|
const d = dir(t.job);
|
|
3156
3575
|
const main = t.tiket.jenis === "klip" ? "klip.json" : "proyek.json";
|
|
3157
|
-
const entries = await listZip(
|
|
3576
|
+
const entries = await listZip(path15.join(d, "paket.zip"));
|
|
3158
3577
|
const names = entries.map((x) => x.name).filter((n) => !n.endsWith("/"));
|
|
3159
3578
|
if (names.some((n) => n.startsWith("/") || n.includes("..") || n.includes("\\") || n !== main && !/^aset\/[\w-]+$/.test(n)))
|
|
3160
3579
|
throw new Error(EngineError.BadPackage);
|
|
@@ -3162,10 +3581,10 @@ async function createRenderService(o) {
|
|
|
3162
3581
|
throw new Error(`Paket tidak berisi ${main}.`);
|
|
3163
3582
|
if (entries.reduce((a, x) => a + x.size, 0) > maxUnzippedMb * 1048576)
|
|
3164
3583
|
throw new Error("Isi paket terlalu besar.");
|
|
3165
|
-
await extractZip(
|
|
3166
|
-
await fsp4.rm(
|
|
3167
|
-
const j = JSON.parse(await fsp4.readFile(
|
|
3168
|
-
const has = (id) => /^[\w-]+$/.test(id) &&
|
|
3584
|
+
await extractZip(path15.join(d, "paket.zip"), path15.join(d, "paket"));
|
|
3585
|
+
await fsp4.rm(path15.join(d, "paket.zip"), { force: true });
|
|
3586
|
+
const j = JSON.parse(await fsp4.readFile(path15.join(d, "paket", main), "utf8"));
|
|
3587
|
+
const has = (id) => /^[\w-]+$/.test(id) && fs19.existsSync(path15.join(d, "paket", "aset", id));
|
|
3169
3588
|
if (main === "klip.json") {
|
|
3170
3589
|
const k = j.klip || {};
|
|
3171
3590
|
const seconds = Number(k.durationInFrames) / Number(k.fps);
|
|
@@ -3213,7 +3632,7 @@ async function createRenderService(o) {
|
|
|
3213
3632
|
job: t.job,
|
|
3214
3633
|
kind: t.tiket.jenis,
|
|
3215
3634
|
dir: dir(t.job),
|
|
3216
|
-
packageDir:
|
|
3635
|
+
packageDir: path15.join(dir(t.job), "paket"),
|
|
3217
3636
|
transparent: !!t.transparan,
|
|
3218
3637
|
persen: t.persen,
|
|
3219
3638
|
width: t.tiket.w,
|
|
@@ -3233,7 +3652,7 @@ async function createRenderService(o) {
|
|
|
3233
3652
|
const size = (await fsp4.stat(h.file)).size;
|
|
3234
3653
|
if (size < 200)
|
|
3235
3654
|
throw new Error(EngineError.EmptyResult);
|
|
3236
|
-
update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas:
|
|
3655
|
+
update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path15.basename(h.file), hasilJenis: h.type });
|
|
3237
3656
|
onJob("done", t);
|
|
3238
3657
|
} catch (e) {
|
|
3239
3658
|
if (t.status !== "batal") {
|
|
@@ -3271,10 +3690,10 @@ async function createRenderService(o) {
|
|
|
3271
3690
|
if (a > z)
|
|
3272
3691
|
return res.writeHead(416, { ...h, "content-range": `bytes */${st.size}` }), res.end();
|
|
3273
3692
|
res.writeHead(206, { ...h, "content-length": z - a + 1, "content-range": `bytes ${a}-${z}/${st.size}` });
|
|
3274
|
-
return void
|
|
3693
|
+
return void fs19.createReadStream(f, { start: a, end: z }).pipe(res);
|
|
3275
3694
|
}
|
|
3276
3695
|
res.writeHead(200, { ...h, "content-length": st.size });
|
|
3277
|
-
|
|
3696
|
+
fs19.createReadStream(f).pipe(res);
|
|
3278
3697
|
}
|
|
3279
3698
|
const ROUTE = /^\/tugas(?:\/(r_[a-f0-9]{16})(\/potongan\/(\d{1,4})|\/mulai|\/hasil)?)?$/;
|
|
3280
3699
|
const server = http2.createServer(async (req, res) => {
|
|
@@ -3313,8 +3732,8 @@ async function createRenderService(o) {
|
|
|
3313
3732
|
if (t.status !== "unggah")
|
|
3314
3733
|
return json(req, res, 409, { galat: "Unggahan sudah ditutup." });
|
|
3315
3734
|
const n = Number(m[3]);
|
|
3316
|
-
const f =
|
|
3317
|
-
const before =
|
|
3735
|
+
const f = path15.join(dir(job), `p${n}`);
|
|
3736
|
+
const before = fs19.existsSync(f) ? (await fsp4.stat(f)).size : 0;
|
|
3318
3737
|
const room = Number(ticket.maksMb) * 1048576 - (t.terunggah - before);
|
|
3319
3738
|
const size = await saveBody2(req, f, Math.min(partMb * 1048576 + 1024, room));
|
|
3320
3739
|
const expected = String(req.headers["x-sha256"] || "").toLowerCase();
|
|
@@ -3336,13 +3755,13 @@ async function createRenderService(o) {
|
|
|
3336
3755
|
const count = Number(b.jumlah);
|
|
3337
3756
|
if (!(count > 0 && count < 1e4))
|
|
3338
3757
|
return json(req, res, 400, { galat: "Jumlah potongan tidak valid." });
|
|
3339
|
-
const zip =
|
|
3340
|
-
const out =
|
|
3758
|
+
const zip = path15.join(dir(job), "paket.zip");
|
|
3759
|
+
const out = fs19.createWriteStream(zip);
|
|
3341
3760
|
const hash = crypto8.createHash("sha256");
|
|
3342
3761
|
let total = 0;
|
|
3343
3762
|
for (let i = 0;i < count; i++) {
|
|
3344
|
-
const f =
|
|
3345
|
-
if (!
|
|
3763
|
+
const f = path15.join(dir(job), `p${i}`);
|
|
3764
|
+
if (!fs19.existsSync(f))
|
|
3346
3765
|
return out.destroy(), json(req, res, 400, { galat: `Potongan ${i + 1} belum terunggah.` });
|
|
3347
3766
|
const part = await fsp4.readFile(f);
|
|
3348
3767
|
hash.update(part);
|
|
@@ -3372,8 +3791,8 @@ async function createRenderService(o) {
|
|
|
3372
3791
|
return json(req, res, 200, summary(t));
|
|
3373
3792
|
}
|
|
3374
3793
|
if (m[2] === "/hasil" && (req.method === "GET" || req.method === "HEAD")) {
|
|
3375
|
-
const f = t.hasilBerkas ?
|
|
3376
|
-
if (t.status !== "selesai" || !f || !
|
|
3794
|
+
const f = t.hasilBerkas ? path15.join(dir(job), t.hasilBerkas) : "";
|
|
3795
|
+
if (t.status !== "selesai" || !f || !fs19.existsSync(f))
|
|
3377
3796
|
return json(req, res, 409, { galat: "Video belum jadi." });
|
|
3378
3797
|
const webm = t.hasilJenis === "video/webm";
|
|
3379
3798
|
return sendFile(req, res, f, webm ? "video/webm" : "video/mp4", `hypeframe-${job}.${webm ? "webm" : "mp4"}`);
|
|
@@ -3404,7 +3823,7 @@ async function createRenderService(o) {
|
|
|
3404
3823
|
if (!JOB_ID.test(job))
|
|
3405
3824
|
continue;
|
|
3406
3825
|
try {
|
|
3407
|
-
const t = JSON.parse(await fsp4.readFile(
|
|
3826
|
+
const t = JSON.parse(await fsp4.readFile(path15.join(dir(job), "status.json"), "utf8"));
|
|
3408
3827
|
if (t.status === "jalan" || t.status === "antre")
|
|
3409
3828
|
update(t, { status: "gagal", galat: EngineError.Restarted });
|
|
3410
3829
|
jobs.set(job, t);
|
|
@@ -3485,7 +3904,7 @@ function table(rows, indent = " ") {
|
|
|
3485
3904
|
}
|
|
3486
3905
|
|
|
3487
3906
|
// src/util/open.ts
|
|
3488
|
-
import { spawn as
|
|
3907
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
3489
3908
|
var PAIRING_LINK = new RegExp(`^https?://[A-Za-z0-9.-]+(:\\d+)?/sambung\\?kode=${PAIRING_CODE.source.slice(1, -1)}$`);
|
|
3490
3909
|
var WEB_ORIGIN = /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?\/?$/;
|
|
3491
3910
|
function openCommand(target, platform, url) {
|
|
@@ -3499,7 +3918,7 @@ function openCommand(target, platform, url) {
|
|
|
3499
3918
|
}
|
|
3500
3919
|
function launch(target, url) {
|
|
3501
3920
|
const [cmd, args] = openCommand(target, isAndroid() ? "android" : process.platform, url);
|
|
3502
|
-
const p =
|
|
3921
|
+
const p = spawn4(cmd, args, { stdio: "ignore", detached: true });
|
|
3503
3922
|
p.on("error", () => {
|
|
3504
3923
|
return;
|
|
3505
3924
|
});
|
|
@@ -3553,6 +3972,8 @@ function logAgentEvent(e) {
|
|
|
3553
3972
|
return log.detail(t("agentLog.option", { agent: e.agent, what: e.what, value: e.value }));
|
|
3554
3973
|
case "stopped":
|
|
3555
3974
|
return log.warn(t("agentLog.stopped", { agent: a, code: String(e.code) }));
|
|
3975
|
+
case "account":
|
|
3976
|
+
return log.info(t("agentLog.account", { agent: a }));
|
|
3556
3977
|
}
|
|
3557
3978
|
}
|
|
3558
3979
|
async function pairDevice(s, noBrowser = false) {
|
|
@@ -3678,13 +4099,14 @@ async function start(args, { fromMenu = false } = {}) {
|
|
|
3678
4099
|
const engineConn = new Connection({ gateway: s.gateway, token: account.token, info: { versi: VERSION, os: osName(), nama: s.name, kemampuan: capabilities, portLokal: service.port }, handler });
|
|
3679
4100
|
conn = engineConn;
|
|
3680
4101
|
setInterval(() => {
|
|
4102
|
+
agents.checkAccounts();
|
|
3681
4103
|
const now = agents.capabilities();
|
|
3682
4104
|
if (JSON.stringify(now) === JSON.stringify(capabilities.agen))
|
|
3683
4105
|
return;
|
|
3684
4106
|
capabilities.agen = now;
|
|
3685
4107
|
conn?.setInfo({ kemampuan: capabilities });
|
|
3686
4108
|
conn?.news("status", { kemampuan: capabilities });
|
|
3687
|
-
},
|
|
4109
|
+
}, 5000).unref();
|
|
3688
4110
|
let connectedBefore = false;
|
|
3689
4111
|
let renderNote = "";
|
|
3690
4112
|
engineConn.on("connected", () => {
|
|
@@ -3801,23 +4223,23 @@ function logout() {
|
|
|
3801
4223
|
|
|
3802
4224
|
// src/cli/commands/autostart.ts
|
|
3803
4225
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
3804
|
-
import
|
|
4226
|
+
import fs20 from "node:fs";
|
|
3805
4227
|
import os3 from "node:os";
|
|
3806
|
-
import
|
|
4228
|
+
import path16 from "node:path";
|
|
3807
4229
|
function entryFile() {
|
|
3808
4230
|
const home = os3.homedir();
|
|
3809
4231
|
if (process.platform === "win32")
|
|
3810
|
-
return
|
|
4232
|
+
return path16.join(process.env.APPDATA || path16.join(home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "HypeFrame.cmd");
|
|
3811
4233
|
if (process.platform === "darwin")
|
|
3812
|
-
return
|
|
4234
|
+
return path16.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
|
|
3813
4235
|
if (hasSystemd())
|
|
3814
|
-
return
|
|
3815
|
-
return
|
|
4236
|
+
return path16.join(home, ".config", "systemd", "user", "hypeframe.service");
|
|
4237
|
+
return path16.join(home, ".config", "autostart", "hypeframe.desktop");
|
|
3816
4238
|
}
|
|
3817
4239
|
function hasSystemd() {
|
|
3818
4240
|
return process.platform === "linux" && spawnSync3("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
|
|
3819
4241
|
}
|
|
3820
|
-
var autostartEnabled = () =>
|
|
4242
|
+
var autostartEnabled = () => fs20.existsSync(entryFile());
|
|
3821
4243
|
var xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
3822
4244
|
function autostart(mode) {
|
|
3823
4245
|
const file = entryFile();
|
|
@@ -3829,7 +4251,7 @@ function autostart(mode) {
|
|
|
3829
4251
|
if (mode === "off") {
|
|
3830
4252
|
if (process.platform === "linux" && file.endsWith(".service"))
|
|
3831
4253
|
spawnSync3("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
|
|
3832
|
-
|
|
4254
|
+
fs20.rmSync(file, { force: true });
|
|
3833
4255
|
log.ok(t("autostart.off"));
|
|
3834
4256
|
return;
|
|
3835
4257
|
}
|
|
@@ -3844,14 +4266,14 @@ function autostart(mode) {
|
|
|
3844
4266
|
return;
|
|
3845
4267
|
}
|
|
3846
4268
|
const quoted = cmd.map((c) => `"${c}"`).join(" ");
|
|
3847
|
-
|
|
4269
|
+
fs20.mkdirSync(path16.dirname(file), { recursive: true });
|
|
3848
4270
|
if (process.platform === "win32") {
|
|
3849
|
-
|
|
4271
|
+
fs20.writeFileSync(file, `@echo off\r
|
|
3850
4272
|
start "HypeFrame" /min ${quoted} start --no-browser\r
|
|
3851
4273
|
`);
|
|
3852
4274
|
} else if (process.platform === "darwin") {
|
|
3853
|
-
const out =
|
|
3854
|
-
|
|
4275
|
+
const out = path16.join(logDir(), "autostart.log");
|
|
4276
|
+
fs20.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
|
|
3855
4277
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3856
4278
|
<plist version="1.0"><dict>
|
|
3857
4279
|
<key>Label</key><string>com.hypeframe.engine</string>
|
|
@@ -3862,7 +4284,7 @@ start "HypeFrame" /min ${quoted} start --no-browser\r
|
|
|
3862
4284
|
</dict></plist>
|
|
3863
4285
|
`);
|
|
3864
4286
|
} else if (file.endsWith(".service")) {
|
|
3865
|
-
|
|
4287
|
+
fs20.writeFileSync(file, `[Unit]
|
|
3866
4288
|
Description=HypeFrame engine
|
|
3867
4289
|
After=network-online.target
|
|
3868
4290
|
|
|
@@ -3877,7 +4299,7 @@ WantedBy=default.target
|
|
|
3877
4299
|
spawnSync3("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
3878
4300
|
spawnSync3("systemctl", ["--user", "enable", "hypeframe.service"], { stdio: "ignore" });
|
|
3879
4301
|
} else {
|
|
3880
|
-
|
|
4302
|
+
fs20.writeFileSync(file, `[Desktop Entry]
|
|
3881
4303
|
Type=Application
|
|
3882
4304
|
Name=HypeFrame engine
|
|
3883
4305
|
Exec=${quoted} start --no-browser
|
|
@@ -3942,6 +4364,7 @@ async function bench(args) {
|
|
|
3942
4364
|
const b = await puppeteer3.launch({
|
|
3943
4365
|
executablePath: chrome,
|
|
3944
4366
|
headless: true,
|
|
4367
|
+
pipe: chromePipe(),
|
|
3945
4368
|
protocolTimeout: 300000,
|
|
3946
4369
|
args: ["--no-first-run", "--disable-extensions", ...s.gpu ? [] : softwareGpuArgs, ...chromePlatformArgs()]
|
|
3947
4370
|
});
|
|
@@ -3979,9 +4402,9 @@ async function bench(args) {
|
|
|
3979
4402
|
import * as p from "@clack/prompts";
|
|
3980
4403
|
|
|
3981
4404
|
// src/agent/install.ts
|
|
3982
|
-
import
|
|
4405
|
+
import fs21 from "node:fs";
|
|
3983
4406
|
import fsp5 from "node:fs/promises";
|
|
3984
|
-
import
|
|
4407
|
+
import path17 from "node:path";
|
|
3985
4408
|
import yauzl2 from "yauzl";
|
|
3986
4409
|
function unzip(file, to) {
|
|
3987
4410
|
return new Promise((ok, fail) => {
|
|
@@ -3989,16 +4412,16 @@ function unzip(file, to) {
|
|
|
3989
4412
|
if (e || !zip)
|
|
3990
4413
|
return fail(e ?? new Error("zip"));
|
|
3991
4414
|
zip.on("entry", (en) => {
|
|
3992
|
-
const target =
|
|
3993
|
-
if (!target.startsWith(to +
|
|
4415
|
+
const target = path17.join(to, en.fileName);
|
|
4416
|
+
if (!target.startsWith(to + path17.sep))
|
|
3994
4417
|
return fail(new Error("archive path outside the agent folder"));
|
|
3995
4418
|
if (en.fileName.endsWith("/"))
|
|
3996
|
-
return
|
|
3997
|
-
|
|
4419
|
+
return fs21.mkdirSync(target, { recursive: true }), zip.readEntry();
|
|
4420
|
+
fs21.mkdirSync(path17.dirname(target), { recursive: true });
|
|
3998
4421
|
zip.openReadStream(en, (e2, s) => {
|
|
3999
4422
|
if (e2 || !s)
|
|
4000
4423
|
return fail(e2 ?? new Error("zip"));
|
|
4001
|
-
const out =
|
|
4424
|
+
const out = fs21.createWriteStream(target);
|
|
4002
4425
|
s.pipe(out);
|
|
4003
4426
|
out.on("finish", () => zip.readEntry());
|
|
4004
4427
|
out.on("error", fail);
|
|
@@ -4013,7 +4436,7 @@ function unzip(file, to) {
|
|
|
4013
4436
|
async function untarGz(file, to) {
|
|
4014
4437
|
const { gunzipSync } = await import("node:zlib");
|
|
4015
4438
|
const data = gunzipSync(await fsp5.readFile(file));
|
|
4016
|
-
const root =
|
|
4439
|
+
const root = path17.resolve(to);
|
|
4017
4440
|
const str = (b) => b.toString("utf8").replace(/\0[\s\S]*$/, "");
|
|
4018
4441
|
const octal = (b) => Number.parseInt(str(b).trim() || "0", 8) || 0;
|
|
4019
4442
|
let off = 0;
|
|
@@ -4044,8 +4467,8 @@ async function untarGz(file, to) {
|
|
|
4044
4467
|
name = name.replace(/^\.\//, "");
|
|
4045
4468
|
if (!name)
|
|
4046
4469
|
continue;
|
|
4047
|
-
const target =
|
|
4048
|
-
if (target !== root && !target.startsWith(root +
|
|
4470
|
+
const target = path17.resolve(root, name);
|
|
4471
|
+
if (target !== root && !target.startsWith(root + path17.sep))
|
|
4049
4472
|
throw new Error("archive path outside the agent folder");
|
|
4050
4473
|
if (type === "5") {
|
|
4051
4474
|
await fsp5.mkdir(target, { recursive: true });
|
|
@@ -4053,22 +4476,22 @@ async function untarGz(file, to) {
|
|
|
4053
4476
|
}
|
|
4054
4477
|
if (type !== "0" && type !== "7")
|
|
4055
4478
|
continue;
|
|
4056
|
-
await fsp5.mkdir(
|
|
4479
|
+
await fsp5.mkdir(path17.dirname(target), { recursive: true });
|
|
4057
4480
|
await fsp5.writeFile(target, body, { mode: octal(h.subarray(100, 108)) & 73 ? 493 : 420 });
|
|
4058
4481
|
}
|
|
4059
4482
|
}
|
|
4060
4483
|
function npxRunner(pkg, extra = []) {
|
|
4061
4484
|
if (isStandalone())
|
|
4062
4485
|
return { cmd: process.execPath, args: ["x", pkg, ...extra], env: { BUN_BE_BUN: "1" } };
|
|
4063
|
-
const npxCli =
|
|
4064
|
-
if (!
|
|
4486
|
+
const npxCli = path17.join(path17.dirname(process.execPath), process.platform === "win32" ? "" : "..", process.platform === "win32" ? "node_modules" : "lib/node_modules", "npm", "bin", "npx-cli.js");
|
|
4487
|
+
if (!fs21.existsSync(npxCli))
|
|
4065
4488
|
throw new Error("npx was not found next to Node.js");
|
|
4066
4489
|
return { cmd: process.execPath, args: [npxCli, "-y", pkg, ...extra], env: {} };
|
|
4067
4490
|
}
|
|
4068
4491
|
function ownCopy(a) {
|
|
4069
4492
|
const bin = a.distribution.binary?.[platformKey()];
|
|
4070
4493
|
if (bin) {
|
|
4071
|
-
const cmd = onPath(
|
|
4494
|
+
const cmd = onPath(path17.basename(bin.cmd).replace(/\.exe$/i, ""));
|
|
4072
4495
|
return cmd ? { cmd, args: bin.args ?? [], env: bin.env ?? {} } : null;
|
|
4073
4496
|
}
|
|
4074
4497
|
const npx = a.distribution.npx;
|
|
@@ -4082,35 +4505,35 @@ function ownCopy(a) {
|
|
|
4082
4505
|
async function unpackBinary(id, version, bin, progress) {
|
|
4083
4506
|
if (!/^[0-9a-f]{64}$/i.test(bin.sha256 || ""))
|
|
4084
4507
|
throw new Error(`Agent ${id}: the registry gives no sha256; not installed`);
|
|
4085
|
-
const dir =
|
|
4508
|
+
const dir = path17.join(agentDir(), id, version);
|
|
4086
4509
|
const tmp = `${dir}.tmp`;
|
|
4087
4510
|
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
4088
4511
|
await fsp5.mkdir(tmp, { recursive: true });
|
|
4089
4512
|
try {
|
|
4090
|
-
const name =
|
|
4513
|
+
const name = path17.basename(new URL(bin.archive).pathname);
|
|
4091
4514
|
const cmdRel = bin.cmd.replace(/^\.\//, "");
|
|
4092
4515
|
if (/\.zip$/i.test(name)) {
|
|
4093
|
-
const file =
|
|
4516
|
+
const file = path17.join(tmp, ".download.zip");
|
|
4094
4517
|
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
|
|
4095
4518
|
await unzip(file, tmp);
|
|
4096
4519
|
await fsp5.rm(file, { force: true });
|
|
4097
4520
|
} else if (/\.(tar\.gz|tgz)$/i.test(name)) {
|
|
4098
|
-
const file =
|
|
4521
|
+
const file = path17.join(tmp, ".download.tar.gz");
|
|
4099
4522
|
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), file, progress);
|
|
4100
4523
|
await untarGz(file, tmp);
|
|
4101
4524
|
await fsp5.rm(file, { force: true });
|
|
4102
4525
|
} else if (/\.gz$/i.test(name)) {
|
|
4103
|
-
await downloadVerified(bin.archive, bin.sha256.toLowerCase(),
|
|
4526
|
+
await downloadVerified(bin.archive, bin.sha256.toLowerCase(), path17.join(tmp, cmdRel), progress, true);
|
|
4104
4527
|
} else
|
|
4105
4528
|
throw new Error(`Agent ${id}: unsupported archive ${name}`);
|
|
4106
|
-
const cmd =
|
|
4107
|
-
if (!
|
|
4529
|
+
const cmd = path17.join(tmp, cmdRel);
|
|
4530
|
+
if (!fs21.existsSync(cmd))
|
|
4108
4531
|
throw new Error(`Agent ${id}: ${bin.cmd} is not in the download`);
|
|
4109
4532
|
if (process.platform !== "win32")
|
|
4110
4533
|
await fsp5.chmod(cmd, 493);
|
|
4111
4534
|
await fsp5.rm(dir, { recursive: true, force: true });
|
|
4112
4535
|
await fsp5.rename(tmp, dir);
|
|
4113
|
-
return { cmd:
|
|
4536
|
+
return { cmd: path17.join(dir, cmdRel), args: bin.args ?? [], env: bin.env ?? {} };
|
|
4114
4537
|
} catch (e) {
|
|
4115
4538
|
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
4116
4539
|
throw e;
|
|
@@ -4130,9 +4553,9 @@ async function codexAcpBuild(arch) {
|
|
|
4130
4553
|
return { url, sha256: sha256.toLowerCase(), version: String(j.tag_name ?? "latest").replace(/^v/, "") };
|
|
4131
4554
|
}
|
|
4132
4555
|
var findFile = (dir, name) => {
|
|
4133
|
-
for (const n of
|
|
4134
|
-
const f =
|
|
4135
|
-
const st =
|
|
4556
|
+
for (const n of fs21.readdirSync(dir)) {
|
|
4557
|
+
const f = path17.join(dir, n);
|
|
4558
|
+
const st = fs21.lstatSync(f);
|
|
4136
4559
|
if (st.isFile() && n === name)
|
|
4137
4560
|
return f;
|
|
4138
4561
|
if (st.isDirectory()) {
|
|
@@ -4152,23 +4575,23 @@ async function installInLinux(a, id, progress, steps, arch) {
|
|
|
4152
4575
|
}
|
|
4153
4576
|
if (id === "codex-acp") {
|
|
4154
4577
|
const b = await codexAcpBuild(arch);
|
|
4155
|
-
const dir =
|
|
4578
|
+
const dir = path17.join(agentDir(), id, b.version);
|
|
4156
4579
|
const tmp = `${dir}.tmp`;
|
|
4157
4580
|
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
4158
4581
|
await fsp5.mkdir(tmp, { recursive: true });
|
|
4159
4582
|
try {
|
|
4160
|
-
const file =
|
|
4583
|
+
const file = path17.join(tmp, ".download.tar.gz");
|
|
4161
4584
|
await downloadVerified(b.url, b.sha256, file, progress);
|
|
4162
4585
|
await untarGz(file, tmp);
|
|
4163
4586
|
await fsp5.rm(file, { force: true });
|
|
4164
4587
|
const found = findFile(tmp, "codex-acp");
|
|
4165
4588
|
if (!found)
|
|
4166
4589
|
throw new Error("codex-acp: the program is not in the download");
|
|
4167
|
-
const rel =
|
|
4590
|
+
const rel = path17.relative(tmp, found);
|
|
4168
4591
|
await fsp5.chmod(found, 493);
|
|
4169
4592
|
await fsp5.rm(dir, { recursive: true, force: true });
|
|
4170
4593
|
await fsp5.rename(tmp, dir);
|
|
4171
|
-
return { launch: { cmd:
|
|
4594
|
+
return { launch: { cmd: path17.join(dir, rel), args: [], env: {}, linux: true }, version: b.version };
|
|
4172
4595
|
} catch (e) {
|
|
4173
4596
|
await fsp5.rm(tmp, { recursive: true, force: true });
|
|
4174
4597
|
throw e;
|
|
@@ -4215,179 +4638,6 @@ async function installAgent(id, progress = () => {
|
|
|
4215
4638
|
return installed;
|
|
4216
4639
|
}
|
|
4217
4640
|
|
|
4218
|
-
// src/agent/login.ts
|
|
4219
|
-
import { spawn as spawn4 } from "node:child_process";
|
|
4220
|
-
var SIGN_IN = /https?:\/\/[^\s"'<>]{8,2000}/g;
|
|
4221
|
-
var looksLikeSignIn = (u) => /oauth|auth|login|signin|sign-in|device|accounts\./i.test(u);
|
|
4222
|
-
function linkScanner(found) {
|
|
4223
|
-
const seen = new Set;
|
|
4224
|
-
let rest = "";
|
|
4225
|
-
return (text) => {
|
|
4226
|
-
rest += text;
|
|
4227
|
-
const end = rest.lastIndexOf(`
|
|
4228
|
-
`);
|
|
4229
|
-
if (end < 0)
|
|
4230
|
-
return void (rest = rest.slice(-4096));
|
|
4231
|
-
const lines = rest.slice(0, end);
|
|
4232
|
-
rest = rest.slice(end + 1);
|
|
4233
|
-
for (const u of lines.match(SIGN_IN) ?? [])
|
|
4234
|
-
if (looksLikeSignIn(u) && !seen.has(u))
|
|
4235
|
-
seen.add(u), found(u);
|
|
4236
|
-
};
|
|
4237
|
-
}
|
|
4238
|
-
function runAttached(cmd, args, env) {
|
|
4239
|
-
return new Promise((done) => {
|
|
4240
|
-
const child = spawn4(cmd, args, { stdio: "inherit", env });
|
|
4241
|
-
child.on("error", () => done(-1));
|
|
4242
|
-
child.on("exit", (code) => done(code));
|
|
4243
|
-
});
|
|
4244
|
-
}
|
|
4245
|
-
async function keyFromShell(name, io) {
|
|
4246
|
-
const value = process.env[name];
|
|
4247
|
-
if (!value)
|
|
4248
|
-
return null;
|
|
4249
|
-
if (io.confirm)
|
|
4250
|
-
return await io.confirm(t("agent.keyFromShellAsk", { name })) ? value : null;
|
|
4251
|
-
io.say(t("agent.keyFromShell", { name }));
|
|
4252
|
-
return value;
|
|
4253
|
-
}
|
|
4254
|
-
async function checkReady(id) {
|
|
4255
|
-
const a = readInstalled().find((x) => x.id === id);
|
|
4256
|
-
if (!a)
|
|
4257
|
-
return false;
|
|
4258
|
-
const proc = new AcpProcess;
|
|
4259
|
-
try {
|
|
4260
|
-
await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
4261
|
-
await proc.request("session/new", { cwd: projectDir("_cek"), mcpServers: [] }, 90000);
|
|
4262
|
-
setReady(id, true);
|
|
4263
|
-
return true;
|
|
4264
|
-
} catch {
|
|
4265
|
-
setReady(id, false);
|
|
4266
|
-
return false;
|
|
4267
|
-
} finally {
|
|
4268
|
-
await proc.stop();
|
|
4269
|
-
}
|
|
4270
|
-
}
|
|
4271
|
-
var isKey = (m) => m.type === "env_var" || !!m.varName;
|
|
4272
|
-
function pick(methods) {
|
|
4273
|
-
return methods.find((m) => m.type === "terminal") ?? methods.find((m) => (!m.type || m.type === "agent") && !isKey(m)) ?? methods.find(isKey);
|
|
4274
|
-
}
|
|
4275
|
-
async function logoutAgent(id) {
|
|
4276
|
-
const a = readInstalled().find((x) => x.id === id);
|
|
4277
|
-
if (!a)
|
|
4278
|
-
throw new Error(`Agent ${id} is not installed`);
|
|
4279
|
-
let signedOut = false;
|
|
4280
|
-
const proc = new AcpProcess;
|
|
4281
|
-
try {
|
|
4282
|
-
const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
4283
|
-
if (init.agentCapabilities?.auth?.logout)
|
|
4284
|
-
signedOut = await proc.request("logout", {}, 60000).then(() => true, () => false) || false;
|
|
4285
|
-
} finally {
|
|
4286
|
-
await proc.stop();
|
|
4287
|
-
}
|
|
4288
|
-
const keys = forgetAgentSecrets(id).length > 0;
|
|
4289
|
-
if (!signedOut && !keys)
|
|
4290
|
-
return "unsupported";
|
|
4291
|
-
setReady(id, false);
|
|
4292
|
-
return signedOut ? "signed-out" : "key-removed";
|
|
4293
|
-
}
|
|
4294
|
-
async function loginAgent(id, io) {
|
|
4295
|
-
const a = readInstalled().find((x) => x.id === id);
|
|
4296
|
-
if (!a)
|
|
4297
|
-
throw new Error(`Agent ${id} is not installed`);
|
|
4298
|
-
const proc = new AcpProcess;
|
|
4299
|
-
let method;
|
|
4300
|
-
if (io.link)
|
|
4301
|
-
proc.on("stderr", linkScanner(io.link));
|
|
4302
|
-
try {
|
|
4303
|
-
const init = await proc.start(a, projectDir("_cek"), agentEnv(id));
|
|
4304
|
-
method = pick(init.authMethods ?? []);
|
|
4305
|
-
if (method && (!method.type || method.type === "agent") && !isKey(method))
|
|
4306
|
-
await proc.request("authenticate", { methodId: method.id }, 10 * 60000);
|
|
4307
|
-
} finally {
|
|
4308
|
-
await proc.stop();
|
|
4309
|
-
}
|
|
4310
|
-
if (method?.type === "terminal") {
|
|
4311
|
-
io.say(method.name || method.description || id);
|
|
4312
|
-
const [cmd, args, env] = agentSpawn(a, { ...agentEnv(id), ...method.env ?? {} }, method.args ?? []);
|
|
4313
|
-
if (await runAttached(cmd, args, env) !== 0)
|
|
4314
|
-
return setReady(id, false), false;
|
|
4315
|
-
} else if (method && isKey(method)) {
|
|
4316
|
-
const name = method.varName || method.id;
|
|
4317
|
-
const value = await keyFromShell(name, io) || await io.ask(name);
|
|
4318
|
-
if (!value)
|
|
4319
|
-
return false;
|
|
4320
|
-
saveAgentEnv(id, { [name]: value.trim() });
|
|
4321
|
-
}
|
|
4322
|
-
return checkReady(id);
|
|
4323
|
-
}
|
|
4324
|
-
|
|
4325
|
-
// src/agent/opencode.ts
|
|
4326
|
-
import fs21 from "node:fs";
|
|
4327
|
-
import path17 from "node:path";
|
|
4328
|
-
var OPENCODE = "opencode";
|
|
4329
|
-
var OPENCODE_KEY = "HF_OPENCODE_KEY";
|
|
4330
|
-
var PROVIDER = "hypeframe";
|
|
4331
|
-
var configFile = () => path17.join(dataDir(), "opencode.json");
|
|
4332
|
-
var cleanUrl = (u) => u.trim().replace(/\/+$/, "");
|
|
4333
|
-
function saveOpencodeApi(api) {
|
|
4334
|
-
const url = cleanUrl(api.url);
|
|
4335
|
-
if (!/^https?:\/\/[^\s/]+/i.test(url))
|
|
4336
|
-
throw new Error("The API address must start with http:// or https://");
|
|
4337
|
-
const models = [...new Set(api.models.map((m) => m.trim()).filter(Boolean))].slice(0, 50);
|
|
4338
|
-
if (!models.length)
|
|
4339
|
-
throw new Error("Pick at least one model");
|
|
4340
|
-
const key = api.key.trim();
|
|
4341
|
-
const config = {
|
|
4342
|
-
$schema: "https://opencode.ai/config.json",
|
|
4343
|
-
provider: {
|
|
4344
|
-
[PROVIDER]: {
|
|
4345
|
-
npm: "@ai-sdk/openai-compatible",
|
|
4346
|
-
name: (api.name || new URL(url).hostname).slice(0, 60),
|
|
4347
|
-
options: { baseURL: url, ...key ? { apiKey: `{env:${OPENCODE_KEY}}` } : {} },
|
|
4348
|
-
models: Object.fromEntries(models.map((m) => [m, { name: m }]))
|
|
4349
|
-
}
|
|
4350
|
-
},
|
|
4351
|
-
model: `${PROVIDER}/${models[0]}`
|
|
4352
|
-
};
|
|
4353
|
-
const f = configFile();
|
|
4354
|
-
fs21.writeFileSync(`${f}.tmp`, `${JSON.stringify(config, null, 2)}
|
|
4355
|
-
`, { mode: 384 });
|
|
4356
|
-
fs21.renameSync(`${f}.tmp`, f);
|
|
4357
|
-
if (key)
|
|
4358
|
-
saveAgentEnv(OPENCODE, { [OPENCODE_KEY]: key, OPENCODE_CONFIG: f });
|
|
4359
|
-
else
|
|
4360
|
-
removeAgentEnv(OPENCODE, [OPENCODE_KEY]), saveAgentEnv(OPENCODE, { OPENCODE_CONFIG: f });
|
|
4361
|
-
return f;
|
|
4362
|
-
}
|
|
4363
|
-
function opencodeApi() {
|
|
4364
|
-
try {
|
|
4365
|
-
const c = JSON.parse(fs21.readFileSync(configFile(), "utf8"));
|
|
4366
|
-
const p = c?.provider?.[PROVIDER];
|
|
4367
|
-
if (!p?.options?.baseURL)
|
|
4368
|
-
return null;
|
|
4369
|
-
return { url: String(p.options.baseURL), name: String(p.name ?? ""), model: String(c.model ?? "").replace(`${PROVIDER}/`, "") };
|
|
4370
|
-
} catch {
|
|
4371
|
-
return null;
|
|
4372
|
-
}
|
|
4373
|
-
}
|
|
4374
|
-
function removeOpencodeApi() {
|
|
4375
|
-
fs21.rmSync(configFile(), { force: true });
|
|
4376
|
-
removeAgentEnv(OPENCODE, [OPENCODE_KEY, "OPENCODE_CONFIG"]);
|
|
4377
|
-
}
|
|
4378
|
-
async function fetchApiModels(url, key, timeoutMs = 1e4) {
|
|
4379
|
-
try {
|
|
4380
|
-
const r = await fetch(`${cleanUrl(url)}/models`, { headers: key.trim() ? { authorization: `Bearer ${key.trim()}` } : {}, signal: AbortSignal.timeout(timeoutMs) });
|
|
4381
|
-
if (!r.ok)
|
|
4382
|
-
return [];
|
|
4383
|
-
const j = await r.json();
|
|
4384
|
-
const ids = (Array.isArray(j?.data) ? j.data : []).map((m) => typeof m?.id === "string" ? m.id : "").filter((x) => x && x.length < 200);
|
|
4385
|
-
return [...new Set(ids)].sort();
|
|
4386
|
-
} catch {
|
|
4387
|
-
return [];
|
|
4388
|
-
}
|
|
4389
|
-
}
|
|
4390
|
-
|
|
4391
4641
|
// src/cli/commands/agent.ts
|
|
4392
4642
|
var NAMES = { "antigravity-acp": "Antigravity", "codex-acp": "Codex", opencode: "OpenCode" };
|
|
4393
4643
|
var agentName = (id) => NAMES[id] ?? readInstalled().find((a) => a.id === id)?.name ?? id;
|
|
@@ -4403,10 +4653,10 @@ function agentHint(id, s) {
|
|
|
4403
4653
|
const mark = s === "ready" ? "✔" : s === "login" ? "▲" : "○";
|
|
4404
4654
|
const state = t(s === "ready" ? "agent.ready" : s === "login" ? "agent.needLogin" : "agent.notInstalled");
|
|
4405
4655
|
const api = id === OPENCODE && s !== "none" ? opencodeApi() : null;
|
|
4406
|
-
const account = api ? t("agent.ownApiTag", { host:
|
|
4656
|
+
const account = api ? t("agent.ownApiTag", { host: hostOf2(api.url) }) : ACCOUNT[id] ? t(ACCOUNT[id]) : "";
|
|
4407
4657
|
return `${mark} ${state}${account ? ` · ${account}` : ""}`;
|
|
4408
4658
|
}
|
|
4409
|
-
var
|
|
4659
|
+
var hostOf2 = (u) => {
|
|
4410
4660
|
try {
|
|
4411
4661
|
return new URL(u).host;
|
|
4412
4662
|
} catch {
|
|
@@ -4430,7 +4680,7 @@ async function ownApi() {
|
|
|
4430
4680
|
return;
|
|
4431
4681
|
const main = String(model).trim();
|
|
4432
4682
|
saveOpencodeApi({ url: String(url), key: String(key ?? ""), models: [main, ...list.filter((m) => m !== main).slice(0, 40)] });
|
|
4433
|
-
log.ok(t("agent.apiSaved", { host:
|
|
4683
|
+
log.ok(t("agent.apiSaved", { host: hostOf2(String(url).trim()), model: main }));
|
|
4434
4684
|
if (await checkReady(OPENCODE))
|
|
4435
4685
|
log.detail(t(runningPid() ? "agent.nextRunning" : "agent.nextStart", { name: agentName(OPENCODE) }));
|
|
4436
4686
|
else
|
|
@@ -4560,7 +4810,7 @@ async function agentMenu() {
|
|
|
4560
4810
|
...state === "none" ? [{ value: "add", label: t("agent.add") }] : [],
|
|
4561
4811
|
...state === "login" ? [{ value: "login", label: t("agent.loginNow") }] : [],
|
|
4562
4812
|
...state === "ready" ? [{ value: "switch", label: t("agent.login") }, { value: "logout", label: t("agent.logout") }] : [],
|
|
4563
|
-
...choice === OPENCODE && state !== "none" ? [{ value: "api", label: opencodeApi() ? t("agent.ownApiChange", { host:
|
|
4813
|
+
...choice === OPENCODE && state !== "none" ? [{ value: "api", label: opencodeApi() ? t("agent.ownApiChange", { host: hostOf2(opencodeApi().url) }) : t("agent.ownApi") }, ...opencodeApi() ? [{ value: "api-off", label: t("agent.ownApiOff") }] : []] : [],
|
|
4564
4814
|
...state !== "none" ? [{ value: "remove", label: t("agent.remove") }] : [],
|
|
4565
4815
|
{ value: "", label: color.muted(t("agent.back")) }
|
|
4566
4816
|
]
|