sakuraai 0.0.18 → 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 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);
@@ -1130,11 +1181,11 @@ function send2(sessionId, message, onData, images, model, cwd) {
1130
1181
  const imageArgs = (images ?? []).flatMap((p) => ["-i", p]);
1131
1182
  const modelArgs = model ? ["--model", model] : [];
1132
1183
  const target2 = sessionId ? ["resume", sessionId] : ["--skip-git-repo-check"];
1133
- const child2 = spawn3(codexBin(), ["exec", ...modelArgs, ...target2, ...imageArgs, message], {
1184
+ const child2 = track(spawn3(codexBin(), ["exec", ...modelArgs, ...target2, ...imageArgs, message], {
1134
1185
  cwd,
1135
1186
  stdio: ["ignore", "pipe", "pipe"],
1136
1187
  env: process.env
1137
- });
1188
+ }));
1138
1189
  let out = "";
1139
1190
  let err = "";
1140
1191
  child2.stdout.on("data", (d) => {
@@ -1164,6 +1215,7 @@ var init_codex = __esm({
1164
1215
  "use strict";
1165
1216
  init_parts();
1166
1217
  init_util();
1218
+ init_running();
1167
1219
  CODEX_DIR = path4.join(HOME, ".codex");
1168
1220
  INDEX_PATH = path4.join(CODEX_DIR, "session_index.jsonl");
1169
1221
  SESSIONS_DIR = path4.join(CODEX_DIR, "sessions");
@@ -1521,11 +1573,11 @@ function send3(sessionId, message, onData, images, model, cwd) {
1521
1573
  const fileArgs = (images ?? []).flatMap((p) => ["-f", p]);
1522
1574
  const modelArgs = model ? ["-m", model] : [];
1523
1575
  const sessionArgs = sessionId ? ["-s", sessionId] : [];
1524
- const child2 = spawn4(opencodeBin(), ["run", ...sessionArgs, ...modelArgs, ...fileArgs, message], {
1576
+ const child2 = track(spawn4(opencodeBin(), ["run", ...sessionArgs, ...modelArgs, ...fileArgs, message], {
1525
1577
  cwd,
1526
1578
  stdio: ["ignore", "pipe", "pipe"],
1527
1579
  env: process.env
1528
- });
1580
+ }));
1529
1581
  let out = "";
1530
1582
  let err = "";
1531
1583
  child2.stdout.on("data", (d) => {
@@ -1555,6 +1607,7 @@ var init_opencode = __esm({
1555
1607
  init_sqlite_transcript();
1556
1608
  init_opencode_v2();
1557
1609
  init_util();
1610
+ init_running();
1558
1611
  DB_PATH = path5.join(HOME, ".local", "share", "opencode", "opencode.db");
1559
1612
  MAC_APP_BIN2 = "/Applications/OpenCode.app/Contents/MacOS/opencode-cli";
1560
1613
  }
@@ -1690,10 +1743,10 @@ function send4(sessionId, message, onData, images, _model, cwd) {
1690
1743
  for (const p of images ?? []) args.push("--attach", p);
1691
1744
  args.push("--output-format", "stream-json", "--prompt", message);
1692
1745
  const { cmd, args: argv } = launchArgs(args);
1693
- const child2 = spawn5(cmd, argv, {
1746
+ const child2 = track(spawn5(cmd, argv, {
1694
1747
  stdio: ["ignore", "pipe", "pipe"],
1695
1748
  env: cliEnv()
1696
- });
1749
+ }));
1697
1750
  let buf = "";
1698
1751
  let streamed = "";
1699
1752
  let response = null;
@@ -1744,6 +1797,7 @@ var init_zcode = __esm({
1744
1797
  "use strict";
1745
1798
  init_sqlite_transcript();
1746
1799
  init_util();
1800
+ init_running();
1747
1801
  DB_PATH2 = path6.join(HOME, ".zcode", "cli", "db", "db.sqlite");
1748
1802
  MAC_APP_CJS = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
1749
1803
  DESKTOP_CONFIG = path6.join(HOME, ".zcode", "v2", "config.json");
@@ -1924,11 +1978,11 @@ function send5(sessionId, message, onData, images, _model, dir) {
1924
1978
  ${refs}` : refs;
1925
1979
  }
1926
1980
  const sessionArgs = sessionId ? ["--session-id", sessionId] : [];
1927
- const child2 = spawn6(dshBin(), ["headless", "--json", ...sessionArgs, "-"], {
1981
+ const child2 = track(spawn6(dshBin(), ["headless", "--json", ...sessionArgs, "-"], {
1928
1982
  cwd,
1929
1983
  stdio: ["pipe", "pipe", "pipe"],
1930
1984
  env: process.env
1931
- });
1985
+ }));
1932
1986
  child2.stdin.end(prompt);
1933
1987
  let buf = "";
1934
1988
  let streamed = "";
@@ -1978,6 +2032,7 @@ var init_deepseek = __esm({
1978
2032
  "src/runtime/deepseek.ts"() {
1979
2033
  "use strict";
1980
2034
  init_util();
2035
+ init_running();
1981
2036
  SESSIONS_DIR2 = path7.join(HOME, ".dsh", "sessions");
1982
2037
  PROJ_CACHE_DIR = path7.join(HOME, ".dsh", "storages", "session_projcache", "sessions");
1983
2038
  MAC_APP_BIN3 = "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh";
@@ -2298,7 +2353,7 @@ async function send6(sessionId, message, onData, images, model, runOpts = {}) {
2298
2353
  const { cmd, args, env } = launchCommand(a);
2299
2354
  let child2;
2300
2355
  try {
2301
- 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 } }));
2302
2357
  } catch (e) {
2303
2358
  return finish(false, e.message);
2304
2359
  }
@@ -2360,9 +2415,9 @@ async function send6(sessionId, message, onData, images, model, runOpts = {}) {
2360
2415
  [Image: ${p}]` };
2361
2416
  }
2362
2417
  const result = await rpc.call("session/prompt", { sessionId: remote, prompt });
2363
- const stop2 = result?.stopReason;
2418
+ const stop3 = result?.stopReason;
2364
2419
  for (const t of tools.values()) if (t.status === "running") t.status = "done";
2365
- if (stop2 === "refusal") return finish(false, `${a.name} declined this request.`);
2420
+ if (stop3 === "refusal") return finish(false, `${a.name} declined this request.`);
2366
2421
  return finish(true);
2367
2422
  } catch (e) {
2368
2423
  const msg = e.message || rpc.lastError() || "the agent failed";
@@ -2381,6 +2436,7 @@ var init_acp = __esm({
2381
2436
  "use strict";
2382
2437
  init_config();
2383
2438
  init_util();
2439
+ init_running();
2384
2440
  run = promisify(execFile);
2385
2441
  REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
2386
2442
  ACP_DIR = path8.join(SAKURA_DIR, "acp");
@@ -2686,11 +2742,11 @@ function create(prompt, opts = {}) {
2686
2742
  }
2687
2743
  function runCreate(cmd, args, cwd, env = process.env) {
2688
2744
  return new Promise((resolve) => {
2689
- const child2 = spawn8(cmd, args, {
2745
+ const child2 = track(spawn8(cmd, args, {
2690
2746
  cwd: cwd || process.cwd(),
2691
2747
  stdio: ["ignore", "pipe", "pipe"],
2692
2748
  env
2693
- });
2749
+ }));
2694
2750
  let out = "";
2695
2751
  let err = "";
2696
2752
  child2.stdout.on("data", (d) => out += d.toString());
@@ -2717,6 +2773,7 @@ var init_sessions = __esm({
2717
2773
  init_deepseek();
2718
2774
  init_acp();
2719
2775
  init_meta();
2776
+ init_running();
2720
2777
  onPath2 = (bin) => path10.isAbsolute(bin) ? fs11.existsSync(bin) : (process.env.PATH ?? "").split(path10.delimiter).some((d) => d && fs11.existsSync(path10.join(d, bin)));
2721
2778
  }
2722
2779
  });
@@ -2750,15 +2807,15 @@ ${text.slice(-PER_CHAT)}`;
2750
2807
 
2751
2808
  ${text || "(empty)"}`);
2752
2809
  }
2753
- let context = blocks.join("\n\n---\n\n");
2754
- if (context.length > TOTAL) context = `[earlier part cut]
2755
- ${context.slice(-TOTAL)}`;
2810
+ let context2 = blocks.join("\n\n---\n\n");
2811
+ if (context2.length > TOTAL) context2 = `[earlier part cut]
2812
+ ${context2.slice(-TOTAL)}`;
2756
2813
  const n = from.length;
2757
2814
  return [
2758
2815
  `<sakura-handoff count="${n}">`,
2759
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.`,
2760
2817
  "",
2761
- context,
2818
+ context2,
2762
2819
  "</sakura-handoff>",
2763
2820
  "",
2764
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."
@@ -4281,8 +4338,10 @@ var init_hub = __esm({
4281
4338
  function turnState(agent, sessionId) {
4282
4339
  return turns.get(sessionKey(agent, sessionId)) ?? null;
4283
4340
  }
4284
- async function runTurn(sessionId, agent, prompt, images, model, run6, launched) {
4341
+ async function runTurn(sessionId, agent, prompt, images, model, run6, launched, launchedHandle) {
4285
4342
  const key = sessionKey(agent, sessionId);
4343
+ const handle2 = launchedHandle ?? newHandle();
4344
+ bindHandle(key, handle2);
4286
4345
  const turn = { status: "running", startedAt: Date.now() };
4287
4346
  turns.set(key, turn);
4288
4347
  const emit = (e) => hub.broadcast(key, e);
@@ -4343,22 +4402,36 @@ async function runTurn(sessionId, agent, prompt, images, model, run6, launched)
4343
4402
  polling = false;
4344
4403
  }
4345
4404
  }, POLL_MS);
4346
- const result = await (launched ? launched(onData) : chat(sessionId, prompt, agent, onData, images, model, run6));
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
+ }
4347
4411
  clearInterval(timer);
4348
- turn.status = result.ok ? "done" : "error";
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";
4349
4420
  turn.finishedAt = Date.now();
4350
- turn.error = result.error;
4421
+ turn.error = error;
4422
+ turn.cancelled = cancelled || void 0;
4351
4423
  emit({
4352
4424
  type: "done",
4353
4425
  sessionId,
4354
4426
  agent,
4355
- ok: result.ok,
4356
- error: result.error,
4427
+ ok: ok2,
4428
+ error,
4429
+ cancelled: cancelled || void 0,
4357
4430
  startedAt: turn.startedAt,
4358
4431
  finishedAt: turn.finishedAt
4359
4432
  });
4360
- notifyTurnEnd(agent, sessionId, result.ok, result.error, stdoutAcc);
4361
- return { ok: result.ok, error: result.error };
4433
+ if (!cancelled) notifyTurnEnd(agent, sessionId, result.ok, result.error, stdoutAcc);
4434
+ return { ok: ok2, error };
4362
4435
  }
4363
4436
  var ANSI, stripAnsi, LIVE_ID, POLL_MS, turns;
4364
4437
  var init_stream = __esm({
@@ -4367,6 +4440,7 @@ var init_stream = __esm({
4367
4440
  init_sessions();
4368
4441
  init_hub();
4369
4442
  init_push();
4443
+ init_running();
4370
4444
  ANSI = /\[[0-9;]*[a-zA-Z]/g;
4371
4445
  stripAnsi = (s) => s.replace(ANSI, "");
4372
4446
  LIVE_ID = "__live__";
@@ -5021,7 +5095,11 @@ async function startChat(agent, prepared, cwd, prompt, model, run6) {
5021
5095
  const before = new Set((await list({ agent, all: true })).map((x) => x.id));
5022
5096
  let sink = null;
5023
5097
  const early = [];
5024
- const done = chatNew(agent, cwd, prompt, (c) => sink ? sink(c) : early.push(c), model);
5098
+ const handle2 = newHandle();
5099
+ const done = withHandle(
5100
+ handle2,
5101
+ () => chatNew(agent, cwd, prompt, (c) => sink ? sink(c) : early.push(c), model)
5102
+ );
5025
5103
  const id = await awaitNewSession(agent, cwd, before, done);
5026
5104
  if (!id) {
5027
5105
  const r = await done;
@@ -5031,7 +5109,7 @@ async function startChat(agent, prepared, cwd, prompt, model, run6) {
5031
5109
  sink = onData;
5032
5110
  early.splice(0).forEach(onData);
5033
5111
  return done;
5034
- }).catch(fail2(id));
5112
+ }, handle2).catch(fail2(id));
5035
5113
  return id;
5036
5114
  }
5037
5115
  function kvToObj(env) {
@@ -5194,6 +5272,7 @@ var init_server = __esm({
5194
5272
  init_zcode();
5195
5273
  init_hub();
5196
5274
  init_stream();
5275
+ init_running();
5197
5276
  init_presence();
5198
5277
  init_terminal();
5199
5278
  init_preview();
@@ -5498,11 +5577,11 @@ var init_server = __esm({
5498
5577
  const r = await runTurn(params.id, agent, String(body?.prompt ?? ""), void 0, model, run6);
5499
5578
  return r.ok ? ok({ ok: true }) : fail("nonzero", r.error ?? "chat failed");
5500
5579
  });
5501
- add3(
5502
- "POST",
5503
- "/sakura/sessions/:id/cancel",
5504
- () => fail("nonzero", "cancel is not supported for local file-backed sessions")
5505
- );
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
+ });
5506
5585
  add3("POST", "/sakura/sessions/:id/rename", ({ params, body }) => {
5507
5586
  const title = String(body?.title ?? "").trim();
5508
5587
  if (!title) return fail("nonzero", "title is required");
@@ -5840,7 +5919,7 @@ function start() {
5840
5919
  }
5841
5920
  throw new Error("daemon did not come up within 5s; check `sakuraai daemon logs`");
5842
5921
  }
5843
- function stop() {
5922
+ function stop2() {
5844
5923
  const info2 = running();
5845
5924
  if (!info2) return false;
5846
5925
  try {
@@ -5852,7 +5931,7 @@ function stop() {
5852
5931
  return true;
5853
5932
  }
5854
5933
  function restart() {
5855
- stop();
5934
+ stop2();
5856
5935
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
5857
5936
  return start();
5858
5937
  }
@@ -6145,7 +6224,7 @@ function registerRuntime(program, version) {
6145
6224
  await showPairing2();
6146
6225
  });
6147
6226
  d.command("stop").description("Stop the background daemon").action(() => {
6148
- stop() ? success("Daemon stopped.") : warn("Daemon was not running.");
6227
+ stop2() ? success("Daemon stopped.") : warn("Daemon was not running.");
6149
6228
  });
6150
6229
  d.command("restart").description("Restart the background daemon").action(() => {
6151
6230
  const i = restart();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sakuraai",
3
- "version": "0.0.18",
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
- await download(url);
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
- await download(url);
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
+ }