hinacode 0.3.0-alpha.14 → 0.3.0-alpha.16

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/out/server/cli.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import { createRequire as __createRequire } from "node:module";
2
2
  globalThis.require ??= __createRequire(import.meta.url);
3
- import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as round, ad as pipeArguments, ae as catchTags, af as fromUndefinedOr, ag as isNotUndefined, ah as getOrUndefined, ai as assignProperty, aj as Service, ak as empty$1, al as exists, am as gen, an as isNone, ao as succeed$3, ap as value, aq as provideService, ar as Stdio, as as catchFilter, at as isQuitError, au as succeed$4, av as fail$1, aw as interrupt, ax as andThen, ay as catchTag, az as result, aA as make$3, aB as provideContext, aC as MinimumLogLevel, aD as Struct, aE as ApprovalRequest, aF as QuestionRequest, aG as SecretRequest, aH as Thread, aI as TaggedError$1, aJ as seconds, aK as decodeUnknownExit, aL as fromJsonString, aM as ServerFrame, aN as acquireRelease, aO as unbounded, aP as endUnsafe, aQ as encodeUnknownEffect, aR as RpcMethods, aS as timeoutOrElse, aT as callback, aU as methodKind, aV as offerUnsafe, aW as WebSocket, aX as REMOTE_PATH, aY as REMOTE_MAX_FRAME_BYTES, aZ as succeedNone, a_ as cliSocketPath, a$ as all, b0 as fromResult, b1 as Number$2, b2 as forEach, b3 as NullOr, b4 as Routine, b5 as AccessMode, b6 as ProviderId, b7 as promise, b8 as isFailure, b9 as toCheckoutTarget, ba as noticeEvents, bb as PushEvent, bc as ThreadStatus, bd as try_, be as as, bf as isThreadBusy, bg as tryPromise, bh as map$4, bi as packageJson, bj as tapError, bk as provide, bl as layer$1 } from "./chunks/remote-CuntvZqY.js";
4
- import { homedir } from "node:os";
5
- import { resolve, sep, join } from "node:path";
3
+ import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as round, ad as pipeArguments, ae as catchTags, af as fromUndefinedOr, ag as isNotUndefined, ah as getOrUndefined, ai as assignProperty, aj as Service, ak as empty$1, al as exists, am as gen, an as isNone, ao as succeed$3, ap as value, aq as provideService, ar as Stdio, as as catchFilter, at as isQuitError, au as succeed$4, av as fail$1, aw as interrupt, ax as andThen, ay as catchTag, az as result, aA as make$3, aB as provideContext, aC as MinimumLogLevel, aD as Struct, aE as ApprovalRequest, aF as QuestionRequest, aG as SecretRequest, aH as Thread, aI as TaggedError$1, aJ as seconds, aK as decodeUnknownExit, aL as fromJsonString, aM as ServerFrame, aN as acquireRelease, aO as unbounded, aP as endUnsafe, aQ as encodeUnknownEffect, aR as RpcMethods, aS as timeoutOrElse, aT as callback, aU as methodKind, aV as offerUnsafe, aW as WebSocket, aX as REMOTE_PATH, aY as REMOTE_MAX_FRAME_BYTES, aZ as succeedNone, a_ as cliSocketPath, a$ as all, b0 as fromResult, b1 as Number$2, b2 as forEach, b3 as NullOr, b4 as Routine, b5 as AccessMode, b6 as ProviderId, b7 as promise, b8 as isFailure, b9 as toCheckoutTarget, ba as noticeEvents, bb as PushEvent, bc as ThreadStatus, bd as try_, be as as, bf as isThreadBusy, bg as tryPromise, bh as map$4, bi as isAlive, bj as packageJson, bk as tapError, bl as provide, bm as layer$1 } from "./chunks/dataDir-ETCSyq0-.js";
4
+ import { homedir, userInfo } from "node:os";
5
+ import { resolve, sep, join, dirname } from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { text } from "node:stream/consumers";
8
- import "node:fs";
8
+ import { execFile } from "node:child_process";
9
+ import { accessSync, constants, readFileSync } from "node:fs";
10
+ import { mkdir, writeFile, rm } from "node:fs/promises";
11
+ import { isSea } from "node:sea";
12
+ import { setTimeout } from "node:timers/promises";
13
+ import { promisify } from "node:util";
9
14
  import "node:url";
10
15
  import "node:readline";
11
- import "node:child_process";
12
16
  import "node:stream";
13
17
  import "stream";
14
18
  import "events";
@@ -3566,7 +3570,7 @@ const Proto = {
3566
3570
  const makeCommand = (options) => {
3567
3571
  const config = options.config;
3568
3572
  const contextConfig = options.contextConfig ?? emptyConfig;
3569
- const service = options.service ?? Service(`${TypeId}/${options.name}`);
3573
+ const service2 = options.service ?? Service(`${TypeId}/${options.name}`);
3570
3574
  const annotations = options.annotations ?? empty$1();
3571
3575
  const globalFlags = options.globalFlags ?? [];
3572
3576
  const subcommands = options.subcommands ?? [];
@@ -3652,7 +3656,7 @@ const makeCommand = (options) => {
3652
3656
  unlisted: options.unlisted ?? false,
3653
3657
  config,
3654
3658
  contextConfig,
3655
- service,
3659
+ service: service2,
3656
3660
  parse,
3657
3661
  parseContext,
3658
3662
  handle,
@@ -5905,12 +5909,192 @@ const pair = make(
5905
5909
  () => flatMap$1(cloudData, (userData) => runDaemon("pair", (daemon) => daemon.pair(userData)))
5906
5910
  ).pipe(withDescription("Print the pairing URLs and QR code of the cloud again, without restarting it."));
5907
5911
  const cloudCommands = [serve, pair];
5912
+ const SERVICE_LABEL = "ai.hinacode.serve";
5913
+ const SYSTEMD_UNIT = "hinacode.service";
5914
+ const STOP_WAIT_MS = 8e3;
5915
+ const xml = (text2) => text2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
5916
+ const xmlString = (text2) => `<string>${xml(text2)}</string>`;
5917
+ const launchdPlist = ({ command, env, home }, log2) => [
5918
+ `<?xml version="1.0" encoding="UTF-8"?>`,
5919
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
5920
+ `<plist version="1.0">`,
5921
+ `<dict>`,
5922
+ ` <key>Label</key>`,
5923
+ ` ${xmlString(SERVICE_LABEL)}`,
5924
+ ` <key>ProgramArguments</key>`,
5925
+ ` <array>`,
5926
+ ...command.map((word) => ` ${xmlString(word)}`),
5927
+ ` </array>`,
5928
+ ` <key>EnvironmentVariables</key>`,
5929
+ ` <dict>`,
5930
+ ...Object.entries({ ...env, HINACODE_SERVE_LOG: log2 }).flatMap(([name, value2]) => [
5931
+ ` <key>${xml(name)}</key>`,
5932
+ ` ${xmlString(value2)}`
5933
+ ]),
5934
+ ` </dict>`,
5935
+ ` <key>WorkingDirectory</key>`,
5936
+ ` ${xmlString(home)}`,
5937
+ ` <key>RunAtLoad</key>`,
5938
+ ` <true/>`,
5939
+ ` <key>KeepAlive</key>`,
5940
+ ` <true/>`,
5941
+ ` <key>StandardOutPath</key>`,
5942
+ ` ${xmlString(log2)}`,
5943
+ ` <key>StandardErrorPath</key>`,
5944
+ ` ${xmlString(log2)}`,
5945
+ `</dict>`,
5946
+ `</plist>`,
5947
+ ``
5948
+ ].join("\n");
5949
+ const systemdQuoted = (text2) => `"${text2.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
5950
+ const systemdUnit = ({ command, env }) => [
5951
+ `[Unit]`,
5952
+ `Description=HinaCode cloud`,
5953
+ ``,
5954
+ `[Service]`,
5955
+ `ExecStart=${command.map((word) => systemdQuoted(word).replaceAll("$", () => "$$")).join(" ")}`,
5956
+ ...Object.entries(env).map(([name, value2]) => `Environment=${systemdQuoted(`${name}=${value2}`)}`),
5957
+ `Restart=on-failure`,
5958
+ ``,
5959
+ `[Install]`,
5960
+ `WantedBy=default.target`,
5961
+ ``
5962
+ ].join("\n");
5963
+ const isExecutable = (path) => {
5964
+ try {
5965
+ accessSync(path, constants.X_OK);
5966
+ return true;
5967
+ } catch {
5968
+ return false;
5969
+ }
5970
+ };
5971
+ const serveCommand = (running) => {
5972
+ const program = running.sea ? running.execPath : running.script;
5973
+ const install2 = "Install it with npm install -g --allow-scripts=node-pty hinacode, or use the executable from a release.";
5974
+ if (program === void 0 || program.split(sep).includes("_npx")) {
5975
+ return fail(usageError(`the service needs a hinacode that stays where it is. ${install2}`));
5976
+ }
5977
+ if (!running.executable(program)) return fail(usageError(`${program} cannot run on its own. ${install2}`));
5978
+ return succeed$2([program, "serve"]);
5979
+ };
5980
+ const execFileAsync = promisify(execFile);
5981
+ const exec = (file, args) => execFileAsync(file, [...args]).then(
5982
+ ({ stdout }) => stdout.trim(),
5983
+ (error2) => {
5984
+ throw new Error(error2.stderr?.trim() || error2.message, { cause: error2 });
5985
+ }
5986
+ );
5987
+ const quietly = (file, args) => exec(file, args).catch(() => "");
5988
+ const servePid = (userData) => {
5989
+ try {
5990
+ const pid = Number(readFileSync(join(userData, "daemon.pid"), "utf8"));
5991
+ return Number.isInteger(pid) && pid > 0 && isAlive(pid) ? pid : void 0;
5992
+ } catch {
5993
+ return void 0;
5994
+ }
5995
+ };
5996
+ const waitUntilFree = async (userData) => {
5997
+ for (let waited = 0; waited < STOP_WAIT_MS; waited += 200) {
5998
+ if (servePid(userData) === void 0) return;
5999
+ await setTimeout(200);
6000
+ }
6001
+ const pid = servePid(userData);
6002
+ if (pid !== void 0) {
6003
+ throw new Error(`another hinacode serve (pid ${pid}) uses ${userData}. Stop it, then install the service again.`);
6004
+ }
6005
+ };
6006
+ const launchd = (home) => ({
6007
+ plist: join(home, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`),
6008
+ log: join(home, "Library", "Logs", "hinacode", "serve.log"),
6009
+ domain: `gui/${process.getuid?.() ?? 0}`
6010
+ });
6011
+ const systemdUnitPath = (home) => join(process.env["XDG_CONFIG_HOME"] || join(home, ".config"), "systemd", "user", SYSTEMD_UNIT);
6012
+ const lingerHint = async () => {
6013
+ const { username } = userInfo();
6014
+ const linger = await quietly("loginctl", ["show-user", username, "--property=Linger", "--value"]);
6015
+ return linger === "no" ? [`Run loginctl enable-linger ${username} to start it at boot without logging in.`] : [];
6016
+ };
6017
+ const install = async (spec, userData) => {
6018
+ if (process.platform === "darwin") {
6019
+ const { plist, log: log2, domain } = launchd(spec.home);
6020
+ await quietly("launchctl", ["bootout", `${domain}/${SERVICE_LABEL}`]);
6021
+ await waitUntilFree(userData);
6022
+ await mkdir(dirname(plist), { recursive: true });
6023
+ await mkdir(dirname(log2), { recursive: true });
6024
+ await writeFile(plist, launchdPlist(spec, log2));
6025
+ await exec("launchctl", ["bootstrap", domain, plist]);
6026
+ return [`Started ${SERVICE_LABEL} from ${plist}.`, `Log: ${log2}`];
6027
+ }
6028
+ const unit = systemdUnitPath(spec.home);
6029
+ await quietly("systemctl", ["--user", "stop", SYSTEMD_UNIT]);
6030
+ await waitUntilFree(userData);
6031
+ await mkdir(dirname(unit), { recursive: true });
6032
+ await writeFile(unit, systemdUnit(spec));
6033
+ await exec("systemctl", ["--user", "daemon-reload"]);
6034
+ await exec("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT]);
6035
+ return [`Started ${SYSTEMD_UNIT} from ${unit}.`, `Log: journalctl --user -u hinacode -f`, ...await lingerHint()];
6036
+ };
6037
+ const uninstall = async (home) => {
6038
+ if (process.platform === "darwin") {
6039
+ const { plist, domain } = launchd(home);
6040
+ await quietly("launchctl", ["bootout", `${domain}/${SERVICE_LABEL}`]);
6041
+ await rm(plist, { force: true });
6042
+ return [`Removed ${plist}.`];
6043
+ }
6044
+ const unit = systemdUnitPath(home);
6045
+ await quietly("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT]);
6046
+ await rm(unit, { force: true });
6047
+ await exec("systemctl", ["--user", "daemon-reload"]);
6048
+ return [`Removed ${unit}.`];
6049
+ };
6050
+ const supported = suspend(
6051
+ () => process.platform === "darwin" || process.platform === "linux" ? void_ : fail(usageError("hinacode service runs on macOS and Linux"))
6052
+ );
6053
+ const report = (command, work) => supported.pipe(
6054
+ andThen(
6055
+ tryPromise({
6056
+ try: work,
6057
+ catch: (error2) => new CliFailure({
6058
+ code: EXIT.failed,
6059
+ message: `service ${command}: ${error2 instanceof Error ? error2.message : String(error2)}`
6060
+ })
6061
+ })
6062
+ ),
6063
+ flatMap$1((lines2) => sync$1(() => process.stdout.write(`${lines2.join("\n")}
6064
+ `)))
6065
+ );
6066
+ const installCommand = make(
6067
+ "install",
6068
+ {},
6069
+ () => gen(function* () {
6070
+ const userData = resolve(yield* cloudData);
6071
+ const command = yield* serveCommand({
6072
+ sea: isSea(),
6073
+ execPath: process.execPath,
6074
+ script: process.argv[1],
6075
+ executable: isExecutable
6076
+ });
6077
+ const env = { PATH: process.env["PATH"] || "/usr/bin:/bin", HINACODE_USER_DATA: userData };
6078
+ yield* report("install", () => install({ command, env, home: homedir() }, userData));
6079
+ })
6080
+ ).pipe(
6081
+ withDescription(
6082
+ "Run hinacode serve as a user service that starts at login and restarts when it stops: launchd on macOS, systemd on Linux. Run it again to rewrite the service."
6083
+ )
6084
+ );
6085
+ const uninstallCommand = make("uninstall", {}, () => report("uninstall", () => uninstall(homedir()))).pipe(
6086
+ withDescription("Stop the service and remove it. The data directory stays.")
6087
+ );
6088
+ const service = make("service").pipe(
6089
+ withDescription("Install or remove hinacode serve as a service on this machine."),
6090
+ withSubcommands([installCommand, uninstallCommand])
6091
+ );
5908
6092
  const { version } = packageJson;
5909
6093
  const hinacode = make("hinacode").pipe(
5910
6094
  withDescription(
5911
6095
  "Drive the agents HinaCode runs on every machine you reach, from scripts and other programs. Every command prints one JSON document on stdout, except watch, which prints one JSON line per event."
5912
6096
  ),
5913
- withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands]),
6097
+ withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands, service]),
5914
6098
  withGlobalFlags([DataDir])
5915
6099
  );
5916
6100
  const exitCode = (exit) => {