sakuraai 0.0.17 → 0.0.19
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/dist/index.js +344 -61
- package/package.json +2 -1
- package/scripts/download-onboard.js +3 -30
- package/scripts/download-tsnet.js +3 -30
- package/scripts/fetch-binary.js +107 -0
package/dist/index.js
CHANGED
|
@@ -577,6 +577,56 @@ var init_util = __esm({
|
|
|
577
577
|
}
|
|
578
578
|
});
|
|
579
579
|
|
|
580
|
+
// src/runtime/running.ts
|
|
581
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
582
|
+
function withHandle(handle2, fn) {
|
|
583
|
+
return context.run(handle2, fn);
|
|
584
|
+
}
|
|
585
|
+
function bindHandle(key, handle2) {
|
|
586
|
+
byKey.set(key, handle2);
|
|
587
|
+
}
|
|
588
|
+
function unbindHandle(key, handle2) {
|
|
589
|
+
if (byKey.get(key) === handle2) byKey.delete(key);
|
|
590
|
+
}
|
|
591
|
+
function stop(child2) {
|
|
592
|
+
try {
|
|
593
|
+
child2.kill("SIGINT");
|
|
594
|
+
} catch {
|
|
595
|
+
}
|
|
596
|
+
setTimeout(() => {
|
|
597
|
+
if (child2.exitCode == null && child2.signalCode == null) {
|
|
598
|
+
try {
|
|
599
|
+
child2.kill("SIGKILL");
|
|
600
|
+
} catch {
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}, 2500).unref();
|
|
604
|
+
}
|
|
605
|
+
function track(child2) {
|
|
606
|
+
const handle2 = context.getStore();
|
|
607
|
+
if (!handle2) return child2;
|
|
608
|
+
handle2.children.add(child2);
|
|
609
|
+
child2.once("exit", () => handle2.children.delete(child2));
|
|
610
|
+
if (handle2.cancelled) stop(child2);
|
|
611
|
+
return child2;
|
|
612
|
+
}
|
|
613
|
+
function cancel(key) {
|
|
614
|
+
const handle2 = byKey.get(key);
|
|
615
|
+
if (!handle2) return false;
|
|
616
|
+
handle2.cancelled = true;
|
|
617
|
+
handle2.children.forEach(stop);
|
|
618
|
+
return true;
|
|
619
|
+
}
|
|
620
|
+
var context, byKey, newHandle;
|
|
621
|
+
var init_running = __esm({
|
|
622
|
+
"src/runtime/running.ts"() {
|
|
623
|
+
"use strict";
|
|
624
|
+
context = new AsyncLocalStorage();
|
|
625
|
+
byKey = /* @__PURE__ */ new Map();
|
|
626
|
+
newHandle = () => ({ children: /* @__PURE__ */ new Set(), cancelled: false });
|
|
627
|
+
}
|
|
628
|
+
});
|
|
629
|
+
|
|
580
630
|
// src/runtime/claude.ts
|
|
581
631
|
import fs3 from "fs";
|
|
582
632
|
import path3 from "path";
|
|
@@ -803,7 +853,7 @@ ${refs}` : refs;
|
|
|
803
853
|
...run6.mode ? ["--permission-mode", run6.mode] : [],
|
|
804
854
|
...run6.fast ? ["--settings", JSON.stringify({ fastMode: true })] : []
|
|
805
855
|
];
|
|
806
|
-
const child2 = spawn2(
|
|
856
|
+
const child2 = track(spawn2(
|
|
807
857
|
bin,
|
|
808
858
|
[
|
|
809
859
|
newCwd ? "--session-id" : "--resume",
|
|
@@ -821,7 +871,7 @@ ${refs}` : refs;
|
|
|
821
871
|
cwd: cwd && fs3.existsSync(cwd) ? cwd : void 0,
|
|
822
872
|
stdio: ["ignore", "pipe", "pipe"]
|
|
823
873
|
}
|
|
824
|
-
);
|
|
874
|
+
));
|
|
825
875
|
let buf = "";
|
|
826
876
|
let finalText = "";
|
|
827
877
|
let err = "";
|
|
@@ -867,6 +917,7 @@ var init_claude = __esm({
|
|
|
867
917
|
"use strict";
|
|
868
918
|
init_parts();
|
|
869
919
|
init_util();
|
|
920
|
+
init_running();
|
|
870
921
|
PROJECTS_DIR = path3.join(HOME, ".claude", "projects");
|
|
871
922
|
pendingNew = /* @__PURE__ */ new Map();
|
|
872
923
|
pendingCwd = (sessionId) => pendingNew.get(sessionId);
|
|
@@ -882,7 +933,7 @@ function codexBin() {
|
|
|
882
933
|
if (fs4.existsSync(MAC_APP_BIN)) return MAC_APP_BIN;
|
|
883
934
|
return "codex";
|
|
884
935
|
}
|
|
885
|
-
function
|
|
936
|
+
function indexSessions() {
|
|
886
937
|
const host = hostname();
|
|
887
938
|
const now = nowSecs();
|
|
888
939
|
let content;
|
|
@@ -919,6 +970,61 @@ function listSessions2() {
|
|
|
919
970
|
}
|
|
920
971
|
return out;
|
|
921
972
|
}
|
|
973
|
+
function stateDbPath() {
|
|
974
|
+
try {
|
|
975
|
+
const dbs = fs4.readdirSync(CODEX_DIR).filter((f) => /^state_\d+\.sqlite$/.test(f));
|
|
976
|
+
const latest = dbs.sort((a, b) => Number(a.match(/\d+/)[0]) - Number(b.match(/\d+/)[0])).pop();
|
|
977
|
+
return latest ? path4.join(CODEX_DIR, latest) : null;
|
|
978
|
+
} catch {
|
|
979
|
+
return null;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
async function stateSessions() {
|
|
983
|
+
const file2 = stateDbPath();
|
|
984
|
+
if (!file2) return null;
|
|
985
|
+
try {
|
|
986
|
+
const mod = await import("better-sqlite3");
|
|
987
|
+
const Ctor = mod.default ?? mod;
|
|
988
|
+
const db = new Ctor(file2, { readonly: true, fileMustExist: true });
|
|
989
|
+
try {
|
|
990
|
+
const rows = db.prepare(
|
|
991
|
+
"SELECT id, COALESCE(NULLIF(name, ''), NULLIF(title, ''), NULLIF(first_user_message, ''), 'New session') AS title, updated_at, cwd, archived FROM threads WHERE attached_thread_parent_id IS NULL ORDER BY updated_at DESC"
|
|
992
|
+
).all();
|
|
993
|
+
for (const r of rows) if (r.archived) archivedInCodex.add(r.id);
|
|
994
|
+
const host = hostname();
|
|
995
|
+
const now = nowSecs();
|
|
996
|
+
return rows.filter((r) => !r.archived).map((r) => {
|
|
997
|
+
const age = Math.max(0, now - r.updated_at);
|
|
998
|
+
return {
|
|
999
|
+
id: r.id,
|
|
1000
|
+
title: r.title.split("\n")[0].slice(0, 200),
|
|
1001
|
+
agent: "codex",
|
|
1002
|
+
status: statusFromAge(age),
|
|
1003
|
+
updatedAt: formatAge(age),
|
|
1004
|
+
machine: host,
|
|
1005
|
+
mtime: r.updated_at,
|
|
1006
|
+
cwd: r.cwd || void 0
|
|
1007
|
+
};
|
|
1008
|
+
});
|
|
1009
|
+
} finally {
|
|
1010
|
+
db.close();
|
|
1011
|
+
}
|
|
1012
|
+
} catch {
|
|
1013
|
+
return null;
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
async function listSessions2() {
|
|
1017
|
+
const indexed = indexSessions();
|
|
1018
|
+
const fromState = await stateSessions();
|
|
1019
|
+
if (!fromState) return indexed;
|
|
1020
|
+
const named = new Map(indexed.map((s) => [s.id, s]));
|
|
1021
|
+
const out = fromState.map((s) => {
|
|
1022
|
+
const idx = named.get(s.id);
|
|
1023
|
+
return idx ? { ...s, title: idx.title, mtime: Math.max(s.mtime, idx.mtime), updatedAt: s.mtime >= idx.mtime ? s.updatedAt : idx.updatedAt } : s;
|
|
1024
|
+
});
|
|
1025
|
+
const seen = new Set(out.map((s) => s.id));
|
|
1026
|
+
return [...out, ...indexed.filter((s) => !seen.has(s.id) && !archivedInCodex.has(s.id))];
|
|
1027
|
+
}
|
|
922
1028
|
async function threadCwds() {
|
|
923
1029
|
const out = /* @__PURE__ */ new Map();
|
|
924
1030
|
let dbs = [];
|
|
@@ -1075,11 +1181,11 @@ function send2(sessionId, message, onData, images, model, cwd) {
|
|
|
1075
1181
|
const imageArgs = (images ?? []).flatMap((p) => ["-i", p]);
|
|
1076
1182
|
const modelArgs = model ? ["--model", model] : [];
|
|
1077
1183
|
const target2 = sessionId ? ["resume", sessionId] : ["--skip-git-repo-check"];
|
|
1078
|
-
const child2 = spawn3(codexBin(), ["exec", ...modelArgs, ...target2, ...imageArgs, message], {
|
|
1184
|
+
const child2 = track(spawn3(codexBin(), ["exec", ...modelArgs, ...target2, ...imageArgs, message], {
|
|
1079
1185
|
cwd,
|
|
1080
1186
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1081
1187
|
env: process.env
|
|
1082
|
-
});
|
|
1188
|
+
}));
|
|
1083
1189
|
let out = "";
|
|
1084
1190
|
let err = "";
|
|
1085
1191
|
child2.stdout.on("data", (d) => {
|
|
@@ -1093,21 +1199,28 @@ function send2(sessionId, message, onData, images, model, cwd) {
|
|
|
1093
1199
|
(code) => resolve({
|
|
1094
1200
|
ok: code === 0,
|
|
1095
1201
|
output: out.trim(),
|
|
1096
|
-
error: code === 0 ? void 0 : err
|
|
1202
|
+
error: code === 0 ? void 0 : codexError(err) || `exited ${code}`
|
|
1097
1203
|
})
|
|
1098
1204
|
);
|
|
1099
1205
|
});
|
|
1100
1206
|
}
|
|
1101
|
-
|
|
1207
|
+
function codexError(stderr) {
|
|
1208
|
+
const lines2 = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
1209
|
+
const errors = lines2.filter((l) => /^ERROR:/i.test(l)).map((l) => l.replace(/^ERROR:\s*/i, ""));
|
|
1210
|
+
return errors.at(-1) ?? lines2.at(-1) ?? "";
|
|
1211
|
+
}
|
|
1212
|
+
var CODEX_DIR, INDEX_PATH, SESSIONS_DIR, MAC_APP_BIN, archivedInCodex;
|
|
1102
1213
|
var init_codex = __esm({
|
|
1103
1214
|
"src/runtime/codex.ts"() {
|
|
1104
1215
|
"use strict";
|
|
1105
1216
|
init_parts();
|
|
1106
1217
|
init_util();
|
|
1218
|
+
init_running();
|
|
1107
1219
|
CODEX_DIR = path4.join(HOME, ".codex");
|
|
1108
1220
|
INDEX_PATH = path4.join(CODEX_DIR, "session_index.jsonl");
|
|
1109
1221
|
SESSIONS_DIR = path4.join(CODEX_DIR, "sessions");
|
|
1110
1222
|
MAC_APP_BIN = "/Applications/Codex.app/Contents/Resources/codex";
|
|
1223
|
+
archivedInCodex = /* @__PURE__ */ new Set();
|
|
1111
1224
|
}
|
|
1112
1225
|
});
|
|
1113
1226
|
|
|
@@ -1245,6 +1358,134 @@ var init_sqlite_transcript = __esm({
|
|
|
1245
1358
|
}
|
|
1246
1359
|
});
|
|
1247
1360
|
|
|
1361
|
+
// src/runtime/opencode-v2.ts
|
|
1362
|
+
function hasV2(db) {
|
|
1363
|
+
return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_v2'").get();
|
|
1364
|
+
}
|
|
1365
|
+
function listSessionsV2(db, host) {
|
|
1366
|
+
const now = nowSecs();
|
|
1367
|
+
const rows = db.prepare(
|
|
1368
|
+
"SELECT id, title, time_updated, directory FROM session_v2 WHERE time_archived IS NULL AND parent_id IS NULL ORDER BY time_updated DESC"
|
|
1369
|
+
).all();
|
|
1370
|
+
return rows.map((r) => {
|
|
1371
|
+
const mtime = Math.floor(r.time_updated / 1e3);
|
|
1372
|
+
const age = Math.max(0, now - mtime);
|
|
1373
|
+
return {
|
|
1374
|
+
id: r.id,
|
|
1375
|
+
title: r.title || "New session",
|
|
1376
|
+
agent: "opencode",
|
|
1377
|
+
status: statusFromAge(age),
|
|
1378
|
+
updatedAt: formatAge(age),
|
|
1379
|
+
machine: host,
|
|
1380
|
+
mtime,
|
|
1381
|
+
cwd: r.directory || void 0
|
|
1382
|
+
};
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
function isV2Session(db, sessionId) {
|
|
1386
|
+
return hasV2(db) && !!db.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionId);
|
|
1387
|
+
}
|
|
1388
|
+
function toolFromV2(c) {
|
|
1389
|
+
const st = c.state ?? {};
|
|
1390
|
+
const part = toolPart(String(c.id ?? ""), String(c.name ?? "tool"), st.input);
|
|
1391
|
+
part.status = st.status === "completed" ? "done" : st.status === "error" ? "error" : "running";
|
|
1392
|
+
const md = typeof st.metadata?.diff === "string" ? st.metadata.diff : null;
|
|
1393
|
+
if (md && part.diff) {
|
|
1394
|
+
const lines2 = unifiedLines(md);
|
|
1395
|
+
part.diff = {
|
|
1396
|
+
...part.diff,
|
|
1397
|
+
lines: lines2.slice(0, 300),
|
|
1398
|
+
added: lines2.filter((l) => l.startsWith("+")).length,
|
|
1399
|
+
removed: lines2.filter((l) => l.startsWith("-")).length
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
if (!(part.diff && part.status === "done")) {
|
|
1403
|
+
const text = Array.isArray(st.content) ? st.content.filter((x) => x?.type === "text").map((x) => x.text).join("\n") : void 0;
|
|
1404
|
+
const err = typeof st.error === "string" ? st.error : st.error?.message;
|
|
1405
|
+
part.output = trimOutput(err ?? text);
|
|
1406
|
+
}
|
|
1407
|
+
return part;
|
|
1408
|
+
}
|
|
1409
|
+
function buildMessagesV2(db, sessionId) {
|
|
1410
|
+
const rows = db.prepare(
|
|
1411
|
+
"SELECT id, type, time_created, data FROM session_message WHERE session_id = ? AND type IN ('user', 'assistant') ORDER BY seq ASC"
|
|
1412
|
+
).all(sessionId);
|
|
1413
|
+
const out = [];
|
|
1414
|
+
let current = null;
|
|
1415
|
+
let lastUserMs = null;
|
|
1416
|
+
for (const r of rows) {
|
|
1417
|
+
let v;
|
|
1418
|
+
try {
|
|
1419
|
+
v = JSON.parse(r.data);
|
|
1420
|
+
} catch {
|
|
1421
|
+
continue;
|
|
1422
|
+
}
|
|
1423
|
+
const ts = chronoIso(Math.floor(r.time_created / 1e3));
|
|
1424
|
+
if (r.type === "user") {
|
|
1425
|
+
const parts2 = [];
|
|
1426
|
+
if (typeof v.text === "string" && v.text.trim()) parts2.push({ type: "text", text: v.text });
|
|
1427
|
+
(Array.isArray(v.files) ? v.files : []).forEach((f, i) => {
|
|
1428
|
+
if (typeof f?.mime === "string" && f.mime.startsWith("image/")) {
|
|
1429
|
+
parts2.push({
|
|
1430
|
+
type: "image",
|
|
1431
|
+
url: `/blobs/opencode/${encodeURIComponent(sessionId)}/${encodeURIComponent(`${r.id}:${i}`)}`,
|
|
1432
|
+
mediaType: f.mime
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
});
|
|
1436
|
+
if (!parts2.length) continue;
|
|
1437
|
+
current = null;
|
|
1438
|
+
lastUserMs = r.time_created;
|
|
1439
|
+
out.push({ id: r.id, role: "user", content: textOf(parts2), timestamp: ts, hasToolUse: false, parts: parts2 });
|
|
1440
|
+
continue;
|
|
1441
|
+
}
|
|
1442
|
+
const parts = [];
|
|
1443
|
+
for (const c of Array.isArray(v.content) ? v.content : []) {
|
|
1444
|
+
if (c?.type === "text" && typeof c.text === "string" && c.text.trim()) parts.push({ type: "text", text: c.text });
|
|
1445
|
+
else if (c?.type === "tool") parts.push(toolFromV2(c));
|
|
1446
|
+
}
|
|
1447
|
+
const err = v.error?.message ?? (typeof v.error === "string" ? v.error : void 0);
|
|
1448
|
+
if (!parts.length && err) parts.push({ type: "text", text: `Error: ${err}` });
|
|
1449
|
+
if (!parts.length) continue;
|
|
1450
|
+
if (!current) {
|
|
1451
|
+
current = { id: r.id, role: "assistant", content: "", timestamp: ts, parts: [] };
|
|
1452
|
+
out.push(current);
|
|
1453
|
+
}
|
|
1454
|
+
current.parts.push(...parts);
|
|
1455
|
+
current.content = textOf(current.parts);
|
|
1456
|
+
current.hasToolUse = current.parts.some((p) => p.type === "tool");
|
|
1457
|
+
const t = v.tokens ?? {};
|
|
1458
|
+
const ctx = (t.input ?? 0) + (t.cache?.read ?? 0) + (t.cache?.write ?? 0);
|
|
1459
|
+
if (ctx > 0) current.inputTokens = ctx;
|
|
1460
|
+
if (typeof v.model?.id === "string" && v.model.id) current.model = v.model.id;
|
|
1461
|
+
const end = v.time?.completed ?? r.time_created;
|
|
1462
|
+
if (lastUserMs != null) current.elapsedSecs = Math.max(0, Math.floor((end - lastUserMs) / 1e3));
|
|
1463
|
+
}
|
|
1464
|
+
return out;
|
|
1465
|
+
}
|
|
1466
|
+
function imageV2(db, sessionId, ref) {
|
|
1467
|
+
const cut = ref.lastIndexOf(":");
|
|
1468
|
+
if (cut < 0) return null;
|
|
1469
|
+
const row = db.prepare("SELECT data FROM session_message WHERE id = ? AND session_id = ? LIMIT 1").get(ref.slice(0, cut), sessionId);
|
|
1470
|
+
if (!row) return null;
|
|
1471
|
+
try {
|
|
1472
|
+
const f = JSON.parse(row.data)?.files?.[Number(ref.slice(cut + 1))];
|
|
1473
|
+
if (typeof f?.mime !== "string" || !f.mime.startsWith("image/") || typeof f.data !== "string") return null;
|
|
1474
|
+
const b64 = f.data.replace(/^data:[^;]+;base64,/, "");
|
|
1475
|
+
return { mediaType: f.mime, data: Buffer.from(b64, "base64") };
|
|
1476
|
+
} catch {
|
|
1477
|
+
return null;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
var init_opencode_v2 = __esm({
|
|
1481
|
+
"src/runtime/opencode-v2.ts"() {
|
|
1482
|
+
"use strict";
|
|
1483
|
+
init_parts();
|
|
1484
|
+
init_sqlite_transcript();
|
|
1485
|
+
init_util();
|
|
1486
|
+
}
|
|
1487
|
+
});
|
|
1488
|
+
|
|
1248
1489
|
// src/runtime/opencode.ts
|
|
1249
1490
|
import path5 from "path";
|
|
1250
1491
|
import fs6 from "fs";
|
|
@@ -1283,10 +1524,12 @@ async function listSessions3() {
|
|
|
1283
1524
|
const host = hostname();
|
|
1284
1525
|
const now = nowSecs();
|
|
1285
1526
|
try {
|
|
1527
|
+
const v2 = hasV2(db) ? listSessionsV2(db, host) : [];
|
|
1528
|
+
const seen = new Set(v2.map((x) => x.id));
|
|
1286
1529
|
const rows = db.prepare(
|
|
1287
1530
|
"SELECT id, title, time_updated, directory FROM session WHERE time_archived IS NULL ORDER BY time_updated DESC"
|
|
1288
1531
|
).all();
|
|
1289
|
-
|
|
1532
|
+
const v1 = rows.filter((r) => !seen.has(r.id)).map((r) => {
|
|
1290
1533
|
const mtime = Math.floor(r.time_updated / 1e3);
|
|
1291
1534
|
const age = Math.max(0, now - mtime);
|
|
1292
1535
|
return {
|
|
@@ -1300,6 +1543,7 @@ async function listSessions3() {
|
|
|
1300
1543
|
cwd: r.directory || void 0
|
|
1301
1544
|
};
|
|
1302
1545
|
});
|
|
1546
|
+
return [...v2, ...v1].sort((a, b) => b.mtime - a.mtime);
|
|
1303
1547
|
} finally {
|
|
1304
1548
|
db.close();
|
|
1305
1549
|
}
|
|
@@ -1308,7 +1552,7 @@ async function messages3(sessionId) {
|
|
|
1308
1552
|
const db = await open();
|
|
1309
1553
|
if (!db) return [];
|
|
1310
1554
|
try {
|
|
1311
|
-
return buildMessages(db, "opencode", sessionId);
|
|
1555
|
+
return isV2Session(db, sessionId) ? buildMessagesV2(db, sessionId) : buildMessages(db, "opencode", sessionId);
|
|
1312
1556
|
} finally {
|
|
1313
1557
|
db.close();
|
|
1314
1558
|
}
|
|
@@ -1317,7 +1561,7 @@ async function image(sessionId, partId) {
|
|
|
1317
1561
|
const db = await open();
|
|
1318
1562
|
if (!db) return null;
|
|
1319
1563
|
try {
|
|
1320
|
-
return filePartImage(db, sessionId, partId);
|
|
1564
|
+
return isV2Session(db, sessionId) ? imageV2(db, sessionId, partId) : filePartImage(db, sessionId, partId);
|
|
1321
1565
|
} catch {
|
|
1322
1566
|
return null;
|
|
1323
1567
|
} finally {
|
|
@@ -1329,11 +1573,11 @@ function send3(sessionId, message, onData, images, model, cwd) {
|
|
|
1329
1573
|
const fileArgs = (images ?? []).flatMap((p) => ["-f", p]);
|
|
1330
1574
|
const modelArgs = model ? ["-m", model] : [];
|
|
1331
1575
|
const sessionArgs = sessionId ? ["-s", sessionId] : [];
|
|
1332
|
-
const child2 = spawn4(opencodeBin(), ["run", ...sessionArgs, ...modelArgs, ...fileArgs, message], {
|
|
1576
|
+
const child2 = track(spawn4(opencodeBin(), ["run", ...sessionArgs, ...modelArgs, ...fileArgs, message], {
|
|
1333
1577
|
cwd,
|
|
1334
1578
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1335
1579
|
env: process.env
|
|
1336
|
-
});
|
|
1580
|
+
}));
|
|
1337
1581
|
let out = "";
|
|
1338
1582
|
let err = "";
|
|
1339
1583
|
child2.stdout.on("data", (d) => {
|
|
@@ -1361,7 +1605,9 @@ var init_opencode = __esm({
|
|
|
1361
1605
|
"src/runtime/opencode.ts"() {
|
|
1362
1606
|
"use strict";
|
|
1363
1607
|
init_sqlite_transcript();
|
|
1608
|
+
init_opencode_v2();
|
|
1364
1609
|
init_util();
|
|
1610
|
+
init_running();
|
|
1365
1611
|
DB_PATH = path5.join(HOME, ".local", "share", "opencode", "opencode.db");
|
|
1366
1612
|
MAC_APP_BIN2 = "/Applications/OpenCode.app/Contents/MacOS/opencode-cli";
|
|
1367
1613
|
}
|
|
@@ -1497,10 +1743,10 @@ function send4(sessionId, message, onData, images, _model, cwd) {
|
|
|
1497
1743
|
for (const p of images ?? []) args.push("--attach", p);
|
|
1498
1744
|
args.push("--output-format", "stream-json", "--prompt", message);
|
|
1499
1745
|
const { cmd, args: argv } = launchArgs(args);
|
|
1500
|
-
const child2 = spawn5(cmd, argv, {
|
|
1746
|
+
const child2 = track(spawn5(cmd, argv, {
|
|
1501
1747
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1502
1748
|
env: cliEnv()
|
|
1503
|
-
});
|
|
1749
|
+
}));
|
|
1504
1750
|
let buf = "";
|
|
1505
1751
|
let streamed = "";
|
|
1506
1752
|
let response = null;
|
|
@@ -1551,6 +1797,7 @@ var init_zcode = __esm({
|
|
|
1551
1797
|
"use strict";
|
|
1552
1798
|
init_sqlite_transcript();
|
|
1553
1799
|
init_util();
|
|
1800
|
+
init_running();
|
|
1554
1801
|
DB_PATH2 = path6.join(HOME, ".zcode", "cli", "db", "db.sqlite");
|
|
1555
1802
|
MAC_APP_CJS = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
|
|
1556
1803
|
DESKTOP_CONFIG = path6.join(HOME, ".zcode", "v2", "config.json");
|
|
@@ -1731,11 +1978,11 @@ function send5(sessionId, message, onData, images, _model, dir) {
|
|
|
1731
1978
|
${refs}` : refs;
|
|
1732
1979
|
}
|
|
1733
1980
|
const sessionArgs = sessionId ? ["--session-id", sessionId] : [];
|
|
1734
|
-
const child2 = spawn6(dshBin(), ["headless", "--json", ...sessionArgs, "-"], {
|
|
1981
|
+
const child2 = track(spawn6(dshBin(), ["headless", "--json", ...sessionArgs, "-"], {
|
|
1735
1982
|
cwd,
|
|
1736
1983
|
stdio: ["pipe", "pipe", "pipe"],
|
|
1737
1984
|
env: process.env
|
|
1738
|
-
});
|
|
1985
|
+
}));
|
|
1739
1986
|
child2.stdin.end(prompt);
|
|
1740
1987
|
let buf = "";
|
|
1741
1988
|
let streamed = "";
|
|
@@ -1785,6 +2032,7 @@ var init_deepseek = __esm({
|
|
|
1785
2032
|
"src/runtime/deepseek.ts"() {
|
|
1786
2033
|
"use strict";
|
|
1787
2034
|
init_util();
|
|
2035
|
+
init_running();
|
|
1788
2036
|
SESSIONS_DIR2 = path7.join(HOME, ".dsh", "sessions");
|
|
1789
2037
|
PROJ_CACHE_DIR = path7.join(HOME, ".dsh", "storages", "session_projcache", "sessions");
|
|
1790
2038
|
MAC_APP_BIN3 = "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh";
|
|
@@ -2105,7 +2353,7 @@ async function send6(sessionId, message, onData, images, model, runOpts = {}) {
|
|
|
2105
2353
|
const { cmd, args, env } = launchCommand(a);
|
|
2106
2354
|
let child2;
|
|
2107
2355
|
try {
|
|
2108
|
-
child2 = spawn7(cmd, args, { cwd: fs9.existsSync(s.cwd) ? s.cwd : os5.homedir(), stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...env } });
|
|
2356
|
+
child2 = track(spawn7(cmd, args, { cwd: fs9.existsSync(s.cwd) ? s.cwd : os5.homedir(), stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...env } }));
|
|
2109
2357
|
} catch (e) {
|
|
2110
2358
|
return finish(false, e.message);
|
|
2111
2359
|
}
|
|
@@ -2167,9 +2415,9 @@ async function send6(sessionId, message, onData, images, model, runOpts = {}) {
|
|
|
2167
2415
|
[Image: ${p}]` };
|
|
2168
2416
|
}
|
|
2169
2417
|
const result = await rpc.call("session/prompt", { sessionId: remote, prompt });
|
|
2170
|
-
const
|
|
2418
|
+
const stop3 = result?.stopReason;
|
|
2171
2419
|
for (const t of tools.values()) if (t.status === "running") t.status = "done";
|
|
2172
|
-
if (
|
|
2420
|
+
if (stop3 === "refusal") return finish(false, `${a.name} declined this request.`);
|
|
2173
2421
|
return finish(true);
|
|
2174
2422
|
} catch (e) {
|
|
2175
2423
|
const msg = e.message || rpc.lastError() || "the agent failed";
|
|
@@ -2188,6 +2436,7 @@ var init_acp = __esm({
|
|
|
2188
2436
|
"use strict";
|
|
2189
2437
|
init_config();
|
|
2190
2438
|
init_util();
|
|
2439
|
+
init_running();
|
|
2191
2440
|
run = promisify(execFile);
|
|
2192
2441
|
REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
|
2193
2442
|
ACP_DIR = path8.join(SAKURA_DIR, "acp");
|
|
@@ -2353,7 +2602,7 @@ import path10 from "path";
|
|
|
2353
2602
|
async function list(opts = {}) {
|
|
2354
2603
|
let sessions = [];
|
|
2355
2604
|
if (!opts.agent || opts.agent === "claude") sessions.push(...listSessions());
|
|
2356
|
-
if (!opts.agent || opts.agent === "codex") sessions.push(...listSessions2());
|
|
2605
|
+
if (!opts.agent || opts.agent === "codex") sessions.push(...await listSessions2());
|
|
2357
2606
|
if (!opts.agent || opts.agent === "opencode")
|
|
2358
2607
|
sessions.push(...await listSessions3());
|
|
2359
2608
|
if (!opts.agent || opts.agent === "zcode")
|
|
@@ -2493,11 +2742,11 @@ function create(prompt, opts = {}) {
|
|
|
2493
2742
|
}
|
|
2494
2743
|
function runCreate(cmd, args, cwd, env = process.env) {
|
|
2495
2744
|
return new Promise((resolve) => {
|
|
2496
|
-
const child2 = spawn8(cmd, args, {
|
|
2745
|
+
const child2 = track(spawn8(cmd, args, {
|
|
2497
2746
|
cwd: cwd || process.cwd(),
|
|
2498
2747
|
stdio: ["ignore", "pipe", "pipe"],
|
|
2499
2748
|
env
|
|
2500
|
-
});
|
|
2749
|
+
}));
|
|
2501
2750
|
let out = "";
|
|
2502
2751
|
let err = "";
|
|
2503
2752
|
child2.stdout.on("data", (d) => out += d.toString());
|
|
@@ -2524,6 +2773,7 @@ var init_sessions = __esm({
|
|
|
2524
2773
|
init_deepseek();
|
|
2525
2774
|
init_acp();
|
|
2526
2775
|
init_meta();
|
|
2776
|
+
init_running();
|
|
2527
2777
|
onPath2 = (bin) => path10.isAbsolute(bin) ? fs11.existsSync(bin) : (process.env.PATH ?? "").split(path10.delimiter).some((d) => d && fs11.existsSync(path10.join(d, bin)));
|
|
2528
2778
|
}
|
|
2529
2779
|
});
|
|
@@ -2557,15 +2807,15 @@ ${text.slice(-PER_CHAT)}`;
|
|
|
2557
2807
|
|
|
2558
2808
|
${text || "(empty)"}`);
|
|
2559
2809
|
}
|
|
2560
|
-
let
|
|
2561
|
-
if (
|
|
2562
|
-
${
|
|
2810
|
+
let context2 = blocks.join("\n\n---\n\n");
|
|
2811
|
+
if (context2.length > TOTAL) context2 = `[earlier part cut]
|
|
2812
|
+
${context2.slice(-TOTAL)}`;
|
|
2563
2813
|
const n = from.length;
|
|
2564
2814
|
return [
|
|
2565
2815
|
`<sakura-handoff count="${n}">`,
|
|
2566
2816
|
`You're picking up ${n === 1 ? "a conversation" : `${n} conversations`} the user had with another coding agent in this project. Treat it as your own history: the files it changed are already changed.`,
|
|
2567
2817
|
"",
|
|
2568
|
-
|
|
2818
|
+
context2,
|
|
2569
2819
|
"</sakura-handoff>",
|
|
2570
2820
|
"",
|
|
2571
2821
|
ask?.trim() || "Pick up where this left off: say in a few lines where things stand, then carry on with what was in progress."
|
|
@@ -3825,6 +4075,15 @@ async function claudeModels() {
|
|
|
3825
4075
|
return claudeCache?.models ?? CLAUDE_ALIASES;
|
|
3826
4076
|
}
|
|
3827
4077
|
}
|
|
4078
|
+
function codexCatalog() {
|
|
4079
|
+
try {
|
|
4080
|
+
const d = JSON.parse(fs18.readFileSync(path16.join(HOME, ".codex", "models_cache.json"), "utf8"));
|
|
4081
|
+
const list4 = Array.isArray(d?.models) ? d.models : [];
|
|
4082
|
+
return list4.filter((m) => typeof m?.slug === "string" && m.visibility !== "hide").sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99)).map((m) => ({ id: m.slug, label: m.display_name || m.slug, desc: m.description || void 0 }));
|
|
4083
|
+
} catch {
|
|
4084
|
+
return [];
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
3828
4087
|
function codexModels() {
|
|
3829
4088
|
const out = [{ id: "", label: "Default" }];
|
|
3830
4089
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -3841,24 +4100,24 @@ function codexModels() {
|
|
|
3841
4100
|
}
|
|
3842
4101
|
} catch {
|
|
3843
4102
|
}
|
|
3844
|
-
for (const
|
|
3845
|
-
if (!seen.has(id)) {
|
|
3846
|
-
seen.add(id);
|
|
3847
|
-
out.push(
|
|
4103
|
+
for (const m of codexCatalog()) {
|
|
4104
|
+
if (!seen.has(m.id)) {
|
|
4105
|
+
seen.add(m.id);
|
|
4106
|
+
out.push(m);
|
|
3848
4107
|
}
|
|
3849
4108
|
}
|
|
3850
4109
|
return out;
|
|
3851
4110
|
}
|
|
3852
|
-
function
|
|
3853
|
-
const out = [{ id: "", label: "Default" }];
|
|
3854
|
-
const allowed = /* @__PURE__ */ new Set(["opencode"]);
|
|
4111
|
+
function opencodeCatalog() {
|
|
3855
4112
|
try {
|
|
3856
|
-
|
|
3857
|
-
fs18.readFileSync(path16.join(HOME, ".local", "share", "opencode", "auth.json"), "utf8")
|
|
3858
|
-
);
|
|
3859
|
-
for (const k of Object.keys(auth)) allowed.add(k);
|
|
4113
|
+
return JSON.parse(fs18.readFileSync(path16.join(HOME, ".cache", "opencode", "models.json"), "utf8"));
|
|
3860
4114
|
} catch {
|
|
4115
|
+
return {};
|
|
3861
4116
|
}
|
|
4117
|
+
}
|
|
4118
|
+
function opencodeModels() {
|
|
4119
|
+
const out = [{ id: "", label: "Default" }];
|
|
4120
|
+
const catalog2 = opencodeCatalog();
|
|
3862
4121
|
try {
|
|
3863
4122
|
const raw = execFileSync(opencodeBin(), ["models"], { encoding: "utf8", timeout: 15e3 });
|
|
3864
4123
|
for (const line of raw.split("\n").map((l) => l.trim()).filter(Boolean)) {
|
|
@@ -3866,18 +4125,21 @@ function opencodeModels() {
|
|
|
3866
4125
|
if (slash < 0) continue;
|
|
3867
4126
|
const provider = line.slice(0, slash);
|
|
3868
4127
|
const model = line.slice(slash + 1);
|
|
3869
|
-
|
|
4128
|
+
const info2 = catalog2[provider]?.models?.[model];
|
|
4129
|
+
const cost = info2?.cost;
|
|
4130
|
+
const free = cost ? !cost.input && !cost.output : /(^|-)free$/i.test(model);
|
|
3870
4131
|
out.push({
|
|
3871
4132
|
id: line,
|
|
3872
4133
|
// opencode wants the full provider/model string
|
|
3873
|
-
label: model,
|
|
4134
|
+
label: info2?.name ?? model,
|
|
3874
4135
|
group: OC_PROVIDER_LABELS[provider] ?? provider,
|
|
3875
|
-
free
|
|
4136
|
+
free
|
|
3876
4137
|
});
|
|
3877
4138
|
}
|
|
3878
4139
|
} catch {
|
|
3879
4140
|
}
|
|
3880
|
-
|
|
4141
|
+
const rank = (g) => g === "OpenCode Go" ? 0 : g === "OpenCode Zen" ? 1 : 2;
|
|
4142
|
+
return [out[0], ...out.slice(1).sort((a, b) => rank(a.group) - rank(b.group))];
|
|
3881
4143
|
}
|
|
3882
4144
|
async function listModels(agent) {
|
|
3883
4145
|
if (agent === "codex") return codexModels();
|
|
@@ -3893,7 +4155,7 @@ function zcodeModels() {
|
|
|
3893
4155
|
function deepseekModels() {
|
|
3894
4156
|
return [{ id: "", label: "Default" }];
|
|
3895
4157
|
}
|
|
3896
|
-
var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName,
|
|
4158
|
+
var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName, OC_PROVIDER_LABELS;
|
|
3897
4159
|
var init_models = __esm({
|
|
3898
4160
|
"src/runtime/models.ts"() {
|
|
3899
4161
|
"use strict";
|
|
@@ -3916,7 +4178,6 @@ var init_models = __esm({
|
|
|
3916
4178
|
};
|
|
3917
4179
|
claudeCache = null;
|
|
3918
4180
|
shortName = (display) => display.replace(/^Claude\s+/i, "");
|
|
3919
|
-
CODEX_CURATED = ["gpt-5.5-codex", "gpt-5.5", "gpt-5-codex", "gpt-5"];
|
|
3920
4181
|
OC_PROVIDER_LABELS = {
|
|
3921
4182
|
opencode: "OpenCode Zen",
|
|
3922
4183
|
"opencode-go": "OpenCode Go",
|
|
@@ -4077,8 +4338,10 @@ var init_hub = __esm({
|
|
|
4077
4338
|
function turnState(agent, sessionId) {
|
|
4078
4339
|
return turns.get(sessionKey(agent, sessionId)) ?? null;
|
|
4079
4340
|
}
|
|
4080
|
-
async function runTurn(sessionId, agent, prompt, images, model, run6, launched) {
|
|
4341
|
+
async function runTurn(sessionId, agent, prompt, images, model, run6, launched, launchedHandle) {
|
|
4081
4342
|
const key = sessionKey(agent, sessionId);
|
|
4343
|
+
const handle2 = launchedHandle ?? newHandle();
|
|
4344
|
+
bindHandle(key, handle2);
|
|
4082
4345
|
const turn = { status: "running", startedAt: Date.now() };
|
|
4083
4346
|
turns.set(key, turn);
|
|
4084
4347
|
const emit = (e) => hub.broadcast(key, e);
|
|
@@ -4139,22 +4402,36 @@ async function runTurn(sessionId, agent, prompt, images, model, run6, launched)
|
|
|
4139
4402
|
polling = false;
|
|
4140
4403
|
}
|
|
4141
4404
|
}, POLL_MS);
|
|
4142
|
-
|
|
4405
|
+
let result;
|
|
4406
|
+
try {
|
|
4407
|
+
result = await (launched ? launched(onData) : withHandle(handle2, () => chat(sessionId, prompt, agent, onData, images, model, run6)));
|
|
4408
|
+
} finally {
|
|
4409
|
+
unbindHandle(key, handle2);
|
|
4410
|
+
}
|
|
4143
4411
|
clearInterval(timer);
|
|
4144
|
-
|
|
4412
|
+
const cancelled = handle2.cancelled;
|
|
4413
|
+
const ok2 = result.ok || cancelled;
|
|
4414
|
+
const error = cancelled ? void 0 : result.error;
|
|
4415
|
+
try {
|
|
4416
|
+
pushFresh(await messages7(sessionId, agent));
|
|
4417
|
+
} catch {
|
|
4418
|
+
}
|
|
4419
|
+
turn.status = ok2 ? "done" : "error";
|
|
4145
4420
|
turn.finishedAt = Date.now();
|
|
4146
|
-
turn.error =
|
|
4421
|
+
turn.error = error;
|
|
4422
|
+
turn.cancelled = cancelled || void 0;
|
|
4147
4423
|
emit({
|
|
4148
4424
|
type: "done",
|
|
4149
4425
|
sessionId,
|
|
4150
4426
|
agent,
|
|
4151
|
-
ok:
|
|
4152
|
-
error
|
|
4427
|
+
ok: ok2,
|
|
4428
|
+
error,
|
|
4429
|
+
cancelled: cancelled || void 0,
|
|
4153
4430
|
startedAt: turn.startedAt,
|
|
4154
4431
|
finishedAt: turn.finishedAt
|
|
4155
4432
|
});
|
|
4156
|
-
notifyTurnEnd(agent, sessionId, result.ok, result.error, stdoutAcc);
|
|
4157
|
-
return { ok:
|
|
4433
|
+
if (!cancelled) notifyTurnEnd(agent, sessionId, result.ok, result.error, stdoutAcc);
|
|
4434
|
+
return { ok: ok2, error };
|
|
4158
4435
|
}
|
|
4159
4436
|
var ANSI, stripAnsi, LIVE_ID, POLL_MS, turns;
|
|
4160
4437
|
var init_stream = __esm({
|
|
@@ -4163,6 +4440,7 @@ var init_stream = __esm({
|
|
|
4163
4440
|
init_sessions();
|
|
4164
4441
|
init_hub();
|
|
4165
4442
|
init_push();
|
|
4443
|
+
init_running();
|
|
4166
4444
|
ANSI = /\[[0-9;]*[a-zA-Z]/g;
|
|
4167
4445
|
stripAnsi = (s) => s.replace(ANSI, "");
|
|
4168
4446
|
LIVE_ID = "__live__";
|
|
@@ -4817,7 +5095,11 @@ async function startChat(agent, prepared, cwd, prompt, model, run6) {
|
|
|
4817
5095
|
const before = new Set((await list({ agent, all: true })).map((x) => x.id));
|
|
4818
5096
|
let sink = null;
|
|
4819
5097
|
const early = [];
|
|
4820
|
-
const
|
|
5098
|
+
const handle2 = newHandle();
|
|
5099
|
+
const done = withHandle(
|
|
5100
|
+
handle2,
|
|
5101
|
+
() => chatNew(agent, cwd, prompt, (c) => sink ? sink(c) : early.push(c), model)
|
|
5102
|
+
);
|
|
4821
5103
|
const id = await awaitNewSession(agent, cwd, before, done);
|
|
4822
5104
|
if (!id) {
|
|
4823
5105
|
const r = await done;
|
|
@@ -4827,7 +5109,7 @@ async function startChat(agent, prepared, cwd, prompt, model, run6) {
|
|
|
4827
5109
|
sink = onData;
|
|
4828
5110
|
early.splice(0).forEach(onData);
|
|
4829
5111
|
return done;
|
|
4830
|
-
}).catch(fail2(id));
|
|
5112
|
+
}, handle2).catch(fail2(id));
|
|
4831
5113
|
return id;
|
|
4832
5114
|
}
|
|
4833
5115
|
function kvToObj(env) {
|
|
@@ -4990,6 +5272,7 @@ var init_server = __esm({
|
|
|
4990
5272
|
init_zcode();
|
|
4991
5273
|
init_hub();
|
|
4992
5274
|
init_stream();
|
|
5275
|
+
init_running();
|
|
4993
5276
|
init_presence();
|
|
4994
5277
|
init_terminal();
|
|
4995
5278
|
init_preview();
|
|
@@ -5294,11 +5577,11 @@ var init_server = __esm({
|
|
|
5294
5577
|
const r = await runTurn(params.id, agent, String(body?.prompt ?? ""), void 0, model, run6);
|
|
5295
5578
|
return r.ok ? ok({ ok: true }) : fail("nonzero", r.error ?? "chat failed");
|
|
5296
5579
|
});
|
|
5297
|
-
add3(
|
|
5298
|
-
"
|
|
5299
|
-
"
|
|
5300
|
-
(
|
|
5301
|
-
);
|
|
5580
|
+
add3("POST", "/sakura/sessions/:id/cancel", async ({ params, body, url }) => {
|
|
5581
|
+
const agent = body?.agent || url.searchParams.get("agent") || await detectAgent(params.id);
|
|
5582
|
+
if (!agent) return fail("nonzero", "unknown agent for session");
|
|
5583
|
+
return ok({ stopped: cancel(sessionKey(agent, params.id)) });
|
|
5584
|
+
});
|
|
5302
5585
|
add3("POST", "/sakura/sessions/:id/rename", ({ params, body }) => {
|
|
5303
5586
|
const title = String(body?.title ?? "").trim();
|
|
5304
5587
|
if (!title) return fail("nonzero", "title is required");
|
|
@@ -5636,7 +5919,7 @@ function start() {
|
|
|
5636
5919
|
}
|
|
5637
5920
|
throw new Error("daemon did not come up within 5s; check `sakuraai daemon logs`");
|
|
5638
5921
|
}
|
|
5639
|
-
function
|
|
5922
|
+
function stop2() {
|
|
5640
5923
|
const info2 = running();
|
|
5641
5924
|
if (!info2) return false;
|
|
5642
5925
|
try {
|
|
@@ -5648,7 +5931,7 @@ function stop() {
|
|
|
5648
5931
|
return true;
|
|
5649
5932
|
}
|
|
5650
5933
|
function restart() {
|
|
5651
|
-
|
|
5934
|
+
stop2();
|
|
5652
5935
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
|
|
5653
5936
|
return start();
|
|
5654
5937
|
}
|
|
@@ -5941,7 +6224,7 @@ function registerRuntime(program, version) {
|
|
|
5941
6224
|
await showPairing2();
|
|
5942
6225
|
});
|
|
5943
6226
|
d.command("stop").description("Stop the background daemon").action(() => {
|
|
5944
|
-
|
|
6227
|
+
stop2() ? success("Daemon stopped.") : warn("Daemon was not running.");
|
|
5945
6228
|
});
|
|
5946
6229
|
d.command("restart").description("Restart the background daemon").action(() => {
|
|
5947
6230
|
const i = restart();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sakuraai",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.19",
|
|
4
4
|
"description": "Sakura Agent CLI + local runtime for managing AI coding sessions (Claude Code, Codex, OpenCode, ZCode, DeepSeek) and reaching them privately from the Sakura mobile app over Tailscale",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"!dist/**/*.map",
|
|
32
32
|
"scripts/download-tsnet.js",
|
|
33
33
|
"scripts/download-onboard.js",
|
|
34
|
+
"scripts/fetch-binary.js",
|
|
34
35
|
"README.md"
|
|
35
36
|
],
|
|
36
37
|
"scripts": {
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
import fs from "node:fs";
|
|
11
11
|
import path from "node:path";
|
|
12
|
-
import https from "node:https";
|
|
13
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { fetchBinary } from "./fetch-binary.js";
|
|
14
14
|
|
|
15
15
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
16
|
const pkg = JSON.parse(fs.readFileSync(path.join(here, "..", "package.json"), "utf8"));
|
|
@@ -31,36 +31,9 @@ const tag = process.env.SAKURA_ONBOARD_TAG || `v${pkg.version}`;
|
|
|
31
31
|
const base = process.env.SAKURA_ONBOARD_BASE_URL || `https://github.com/Nishu0/sakura-tsnet/releases/download/${tag}`;
|
|
32
32
|
const url = `${base}/${asset}`;
|
|
33
33
|
|
|
34
|
-
function download(u, redirectsLeft = 5) {
|
|
35
|
-
return new Promise((resolve, reject) => {
|
|
36
|
-
https
|
|
37
|
-
.get(u, { headers: { "User-Agent": "sakuraai-postinstall" } }, (res) => {
|
|
38
|
-
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
|
|
39
|
-
if (redirectsLeft <= 0) return reject(new Error("too many redirects"));
|
|
40
|
-
res.resume();
|
|
41
|
-
return resolve(download(res.headers.location, redirectsLeft - 1));
|
|
42
|
-
}
|
|
43
|
-
if (res.statusCode !== 200) {
|
|
44
|
-
res.resume();
|
|
45
|
-
return reject(new Error(`HTTP ${res.statusCode} for ${u}`));
|
|
46
|
-
}
|
|
47
|
-
fs.mkdirSync(binDir, { recursive: true });
|
|
48
|
-
const tmp = `${outPath}.download`;
|
|
49
|
-
const file = fs.createWriteStream(tmp);
|
|
50
|
-
res.pipe(file);
|
|
51
|
-
file.on("finish", () => file.close(() => {
|
|
52
|
-
fs.renameSync(tmp, outPath);
|
|
53
|
-
if (!isWin) fs.chmodSync(outPath, 0o755);
|
|
54
|
-
resolve();
|
|
55
|
-
}));
|
|
56
|
-
file.on("error", reject);
|
|
57
|
-
})
|
|
58
|
-
.on("error", reject);
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
|
|
62
34
|
try {
|
|
63
|
-
|
|
35
|
+
fs.mkdirSync(binDir, { recursive: true });
|
|
36
|
+
await fetchBinary(url, outPath, "welcome guide");
|
|
64
37
|
console.log(`[sakura] installed welcome guide (${asset}). Run \`sakura welcome\` any time.`);
|
|
65
38
|
} catch {
|
|
66
39
|
// Silent — the CLI falls back to a plain-text guide.
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
import fs from "node:fs";
|
|
11
11
|
import path from "node:path";
|
|
12
|
-
import https from "node:https";
|
|
13
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { fetchBinary } from "./fetch-binary.js";
|
|
14
14
|
|
|
15
15
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
16
|
const pkg = JSON.parse(fs.readFileSync(path.join(here, "..", "package.json"), "utf8"));
|
|
@@ -41,36 +41,9 @@ const tag = process.env.SAKURA_TSNET_TAG || `v${pkg.version}`;
|
|
|
41
41
|
const base = process.env.SAKURA_TSNET_BASE_URL || `https://github.com/Nishu0/sakura-tsnet/releases/download/${tag}`;
|
|
42
42
|
const url = `${base}/${asset}`;
|
|
43
43
|
|
|
44
|
-
function download(u, redirectsLeft = 5) {
|
|
45
|
-
return new Promise((resolve, reject) => {
|
|
46
|
-
https
|
|
47
|
-
.get(u, { headers: { "User-Agent": "sakuraai-postinstall" } }, (res) => {
|
|
48
|
-
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
|
|
49
|
-
if (redirectsLeft <= 0) return reject(new Error("too many redirects"));
|
|
50
|
-
res.resume();
|
|
51
|
-
return resolve(download(res.headers.location, redirectsLeft - 1));
|
|
52
|
-
}
|
|
53
|
-
if (res.statusCode !== 200) {
|
|
54
|
-
res.resume();
|
|
55
|
-
return reject(new Error(`HTTP ${res.statusCode} for ${u}`));
|
|
56
|
-
}
|
|
57
|
-
fs.mkdirSync(binDir, { recursive: true });
|
|
58
|
-
const tmp = `${outPath}.download`;
|
|
59
|
-
const file = fs.createWriteStream(tmp);
|
|
60
|
-
res.pipe(file);
|
|
61
|
-
file.on("finish", () => file.close(() => {
|
|
62
|
-
fs.renameSync(tmp, outPath);
|
|
63
|
-
if (!isWin) fs.chmodSync(outPath, 0o755);
|
|
64
|
-
resolve();
|
|
65
|
-
}));
|
|
66
|
-
file.on("error", reject);
|
|
67
|
-
})
|
|
68
|
-
.on("error", reject);
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
|
|
72
44
|
try {
|
|
73
|
-
|
|
45
|
+
fs.mkdirSync(binDir, { recursive: true });
|
|
46
|
+
await fetchBinary(url, outPath, "network helper");
|
|
74
47
|
console.log(`[sakura] installed embedded-Tailscale sidecar (${asset}).`);
|
|
75
48
|
} catch (e) {
|
|
76
49
|
skip(`could not download ${asset} (${e.message}).`);
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Shared downloader for the postinstall scripts. Shows a progress line and gives
|
|
2
|
+
// up on a stalled connection instead of hanging `npm install` forever.
|
|
3
|
+
//
|
|
4
|
+
// npm swallows lifecycle-script output, so progress is written straight to the
|
|
5
|
+
// terminal (/dev/tty) when there is one; in CI or piped installs it stays quiet.
|
|
6
|
+
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import https from "node:https";
|
|
9
|
+
|
|
10
|
+
const STALL_MS = Number(process.env.SAKURA_DOWNLOAD_STALL_MS) || 30_000; // no bytes for this long → give up
|
|
11
|
+
const TOTAL_MS = Number(process.env.SAKURA_DOWNLOAD_TIMEOUT_MS) || 10 * 60_000; // whole download cap
|
|
12
|
+
|
|
13
|
+
function openTty() {
|
|
14
|
+
if (process.platform === "win32") return null;
|
|
15
|
+
try {
|
|
16
|
+
return fs.openSync("/dev/tty", "w");
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const mb = (n) => (n / 1048576).toFixed(1);
|
|
23
|
+
|
|
24
|
+
function progress(label) {
|
|
25
|
+
const tty = openTty();
|
|
26
|
+
let last = 0;
|
|
27
|
+
let started = Date.now();
|
|
28
|
+
const write = (s) => {
|
|
29
|
+
if (tty == null) return;
|
|
30
|
+
try {
|
|
31
|
+
fs.writeSync(tty, s);
|
|
32
|
+
} catch {}
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
update(done, total) {
|
|
36
|
+
const now = Date.now();
|
|
37
|
+
if (now - last < 200 && done !== total) return;
|
|
38
|
+
last = now;
|
|
39
|
+
const secs = Math.max(0.001, (now - started) / 1000);
|
|
40
|
+
const rate = `${Math.round(done / 1024 / secs)} KB/s`;
|
|
41
|
+
const size = total ? `${mb(done)}/${mb(total)} MB (${Math.floor((done / total) * 100)}%)` : `${mb(done)} MB`;
|
|
42
|
+
write(`\r\x1b[2K[sakura] downloading ${label} ${size} ${rate}`);
|
|
43
|
+
},
|
|
44
|
+
end() {
|
|
45
|
+
write("\r\x1b[2K");
|
|
46
|
+
if (tty != null) try { fs.closeSync(tty); } catch {}
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Download `url` to `outPath` (via a temp file), following redirects. */
|
|
52
|
+
export function fetchBinary(url, outPath, label) {
|
|
53
|
+
const tmp = `${outPath}.download`;
|
|
54
|
+
const bar = progress(label);
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
let settled = false;
|
|
57
|
+
let req;
|
|
58
|
+
const fail = (err) => {
|
|
59
|
+
if (settled) return;
|
|
60
|
+
settled = true;
|
|
61
|
+
clearTimeout(total);
|
|
62
|
+
req?.destroy();
|
|
63
|
+
bar.end();
|
|
64
|
+
try { fs.rmSync(tmp, { force: true }); } catch {}
|
|
65
|
+
reject(err);
|
|
66
|
+
};
|
|
67
|
+
const total = setTimeout(() => fail(new Error(`timed out after ${TOTAL_MS / 60_000} min`)), TOTAL_MS);
|
|
68
|
+
|
|
69
|
+
const get = (u, redirectsLeft) => {
|
|
70
|
+
req = https.get(u, { headers: { "User-Agent": "sakuraai-postinstall" } }, (res) => {
|
|
71
|
+
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
|
|
72
|
+
res.resume();
|
|
73
|
+
if (redirectsLeft <= 0) return fail(new Error("too many redirects"));
|
|
74
|
+
return get(new URL(res.headers.location, u).toString(), redirectsLeft - 1);
|
|
75
|
+
}
|
|
76
|
+
if (res.statusCode !== 200) {
|
|
77
|
+
res.resume();
|
|
78
|
+
return fail(new Error(`HTTP ${res.statusCode} for ${u}`));
|
|
79
|
+
}
|
|
80
|
+
const size = Number(res.headers["content-length"]) || 0;
|
|
81
|
+
let done = 0;
|
|
82
|
+
const file = fs.createWriteStream(tmp);
|
|
83
|
+
res.on("data", (chunk) => {
|
|
84
|
+
done += chunk.length;
|
|
85
|
+
bar.update(done, size);
|
|
86
|
+
});
|
|
87
|
+
res.on("error", fail);
|
|
88
|
+
res.on("aborted", () => fail(new Error("connection closed early")));
|
|
89
|
+
file.on("error", fail);
|
|
90
|
+
res.pipe(file);
|
|
91
|
+
file.on("finish", () => file.close(() => {
|
|
92
|
+
if (settled) return;
|
|
93
|
+
if (size && done < size) return fail(new Error(`incomplete download (${done}/${size} bytes)`));
|
|
94
|
+
settled = true;
|
|
95
|
+
clearTimeout(total);
|
|
96
|
+
bar.end();
|
|
97
|
+
fs.renameSync(tmp, outPath);
|
|
98
|
+
if (process.platform !== "win32") fs.chmodSync(outPath, 0o755);
|
|
99
|
+
resolve();
|
|
100
|
+
}));
|
|
101
|
+
});
|
|
102
|
+
req.setTimeout(STALL_MS, () => fail(new Error(`stalled, no data for ${STALL_MS / 1000}s`)));
|
|
103
|
+
req.on("error", fail);
|
|
104
|
+
};
|
|
105
|
+
get(url, 5);
|
|
106
|
+
});
|
|
107
|
+
}
|