getzopu 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +21 -10
  2. package/dist/getzopu.mjs +725 -144
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -59,16 +59,27 @@ from a tree that is not green on `master`.
59
59
 
60
60
  ### Machines
61
61
 
62
- `getzopu machines connect [--name <name>] [--url <url>]` pairs the computer when it has no
63
- credential — a page to sign in to, a six-digit code to type there — keeps the credential in
64
- `~/.config/zopu/machine/credential.json` (mode `0600`), and then runs the satellite in the
65
- foreground until Ctrl-C. The satellite (`packages/machines/src/satellite/`) dials out to
66
- `/ws/machines` with the credential as a bearer, comes back by itself after a drop (at once the
67
- first time, then on a ladder from 1 s to 30 s), and keeps a journal of every command it ran
68
- (`~/.config/zopu/machine/journal/`), so a command that outlives a drop is picked up where it was.
69
- Commands run as the user, in a process group of their own; nothing is scoped.
70
- `getzopu machines status` says whether the computer is connected; `getzopu machines disconnect`
71
- revokes it on the server and forgets the credential.
62
+ `getzopu machines connect [--name <name>] [--url <url>] [--foreground]` pairs the computer when
63
+ it has no credential — a page to sign in to, a six-digit code to type there — keeps the credential
64
+ in `~/.config/zopu/machine/credential.json` (mode `0600`), and then installs the satellite as a
65
+ service of your account and starts it, so the computer stays reachable with every window closed
66
+ and after a restart: a launch agent on macOS (`~/Library/LaunchAgents/zopu-machines-<hash>.plist`),
67
+ a systemd user unit on Linux (`~/.config/systemd/user/`, with `loginctl enable-linger` asked for),
68
+ a scheduled task on Windows (a hidden launcher hosts the program; it runs while you are signed in).
69
+ No administrator rights. The service runs a copy of this program kept under `~/.config/zopu/machine/`, with the
70
+ runtime that ran `connect`, and writes to `satellite.log` there; it is restarted only when it
71
+ crashes — a revoked or deliberately stopped satellite stays stopped. The service's name carries a
72
+ hash of the machine's home, so a second Zopu on one computer never displaces the first. The shape
73
+ follows t3 code's background service. `--foreground` runs the satellite in the terminal until Ctrl-C
74
+ instead.
75
+
76
+ The satellite (`packages/machines/src/satellite/`) dials out to `/ws/machines` with the credential
77
+ as a bearer, comes back by itself after a drop (at once the first time, then on a ladder from 1 s
78
+ to 30 s), and keeps a journal of every command it ran (`~/.config/zopu/machine/journal/`), so a
79
+ command that outlives a drop is picked up where it was. Commands run as the user, in a process
80
+ group of their own; nothing is scoped. On Windows the command runs in cmd.exe with no console window, and a stop ends its whole process tree. `getzopu machines status` says whether the link is up, how
81
+ the service is, and the last lines of its log; `getzopu machines disconnect` stops and removes the
82
+ service, revokes the computer on the server, and forgets the credential.
72
83
 
73
84
  The image uses `apps/cli` as its build context and embeds the exact self-contained `dist/getzopu.mjs` plus package metadata. The machine-image publish flow (`../infra/scripts/publish-machine-image.sh`, catalog sync, and the `provisioning.ts` digest pin) was removed with the actor package on 2026-11-18; already-published images keep running, but there is no source pin or publish script until provisioning is rebuilt. Image CMD owns bootstrap, so existing pinned images keep their original boot command until replaced.
74
85
 
package/dist/getzopu.mjs CHANGED
@@ -362,7 +362,7 @@ var exports_machine = {};
362
362
  __export(exports_machine, {
363
363
  runMachine: () => runMachine
364
364
  });
365
- import { spawn as spawn3, spawnSync } from "node:child_process";
365
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
366
366
  import {
367
367
  chmodSync,
368
368
  lstatSync,
@@ -375,8 +375,8 @@ import {
375
375
  symlinkSync,
376
376
  writeFileSync
377
377
  } from "node:fs";
378
- import { homedir as homedir5 } from "node:os";
379
- import path3 from "node:path";
378
+ import { homedir as homedir6 } from "node:os";
379
+ import path5 from "node:path";
380
380
  var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH_PORT_ENV = "SSH_PORT", DEFAULT_SSH_PORT = 2222, BootstrapError, sshPortFromEnv = () => {
381
381
  const raw = process.env[SSH_PORT_ENV] ?? "";
382
382
  if (raw === "") {
@@ -388,12 +388,12 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
388
388
  }
389
389
  return port;
390
390
  }, SSHD_ENV, CACHE_ROOT_ENV = "ZOPU_CACHE_ROOT", DEFAULT_CACHE_ROOT = "/workspace/.zopu-cache", CACHE_ROOT, BUDGETED_CACHE_DIRS, DEFAULT_BUDGET_GIB = 2, PRUNE_FRESH_MS, PRUNE_LOCK, STALE_LOCK_MS, cacheSymlinks = () => {
391
- const home = homedir5();
391
+ const home = homedir6();
392
392
  return [
393
- { dir: "npm", target: path3.join(home, ".npm") },
394
- { dir: "bun", target: path3.join(home, ".bun/install/cache") },
395
- { dir: "pip", target: path3.join(home, ".cache/pip") },
396
- { dir: "browsers", target: path3.join(home, ".cache/ms-playwright") }
393
+ { dir: "npm", target: path5.join(home, ".npm") },
394
+ { dir: "bun", target: path5.join(home, ".bun/install/cache") },
395
+ { dir: "pip", target: path5.join(home, ".cache/pip") },
396
+ { dir: "browsers", target: path5.join(home, ".cache/ms-playwright") }
397
397
  ];
398
398
  }, USAGE, fail9 = (message) => {
399
399
  process.stderr.write(`zopu: ${message}
@@ -404,8 +404,8 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
404
404
  if (publicKey === "") {
405
405
  throw new BootstrapError(`${AUTHORIZED_KEY_ENV} is not set. The provisioning layer must pass the session's public key.`);
406
406
  }
407
- const sshDir = path3.join(homedir5(), ".ssh");
408
- const authorizedKeys = path3.join(sshDir, "authorized_keys");
407
+ const sshDir = path5.join(homedir6(), ".ssh");
408
+ const authorizedKeys = path5.join(sshDir, "authorized_keys");
409
409
  mkdirSync(sshDir, { recursive: true });
410
410
  writeFileSync(authorizedKeys, `${publicKey}
411
411
  `);
@@ -413,7 +413,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
413
413
  chmodSync(authorizedKeys, 384);
414
414
  prepareCacheTree();
415
415
  mkdirSync("/run/sshd", { recursive: true });
416
- const hostKeys = spawnSync("ssh-keygen", ["-A"], { stdio: "inherit" });
416
+ const hostKeys = spawnSync2("ssh-keygen", ["-A"], { stdio: "inherit" });
417
417
  if (hostKeys.error !== undefined) {
418
418
  throw new BootstrapError(`cannot run ssh-keygen: ${hostKeys.error.message}`);
419
419
  }
@@ -434,7 +434,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
434
434
  }, prepareCacheTree = () => {
435
435
  for (const name of [...BUDGETED_CACHE_DIRS, "browsers", "xdg"]) {
436
436
  try {
437
- mkdirSync(path3.join(CACHE_ROOT, name), { recursive: true });
437
+ mkdirSync(path5.join(CACHE_ROOT, name), { recursive: true });
438
438
  } catch (error) {
439
439
  const reason = error instanceof Error ? error.message : String(error);
440
440
  process.stderr.write(`zopu: cache dir ${name}: ${reason}
@@ -443,7 +443,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
443
443
  }
444
444
  for (const { dir, target } of cacheSymlinks()) {
445
445
  try {
446
- linkCacheDir(path3.join(CACHE_ROOT, dir), target);
446
+ linkCacheDir(path5.join(CACHE_ROOT, dir), target);
447
447
  } catch (error) {
448
448
  const reason = error instanceof Error ? error.message : String(error);
449
449
  process.stderr.write(`zopu: cache link ${target}: ${reason}
@@ -469,7 +469,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
469
469
  return;
470
470
  }
471
471
  }
472
- mkdirSync(path3.dirname(target), { recursive: true });
472
+ mkdirSync(path5.dirname(target), { recursive: true });
473
473
  symlinkSync(source, target, "dir");
474
474
  }, spawnDetachedPrune = () => {
475
475
  try {
@@ -500,7 +500,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
500
500
  if (argv.length === 0) {
501
501
  continue;
502
502
  }
503
- const exe = path3.basename(argv[0]);
503
+ const exe = path5.basename(argv[0]);
504
504
  if (/^(?:npm|npx|bun|bunx|pip3?|pipx|yarn|pnpm|uv|uvx|python3?)$/u.test(exe) && argv.some((arg) => /^(?:install|i|add|ci|update|upgrade|sync|pip|requirement|-r)/u.test(arg))) {
505
505
  return true;
506
506
  }
@@ -515,7 +515,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
515
515
  return entries3;
516
516
  }
517
517
  for (const name of names) {
518
- const p = path3.join(dir, name);
518
+ const p = path5.join(dir, name);
519
519
  let stats;
520
520
  try {
521
521
  stats = lstatSync(p);
@@ -539,9 +539,9 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
539
539
  }
540
540
  for (const name of names) {
541
541
  try {
542
- const stats = lstatSync(path3.join(p, name));
542
+ const stats = lstatSync(path5.join(p, name));
543
543
  if (stats.isDirectory()) {
544
- total += dirSize(path3.join(p, name));
544
+ total += dirSize(path5.join(p, name));
545
545
  } else if (stats.isFile()) {
546
546
  total += stats.size;
547
547
  }
@@ -561,8 +561,8 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
561
561
  }
562
562
  for (const name of names) {
563
563
  try {
564
- const childStats = lstatSync(path3.join(p, name));
565
- newest = Math.max(newest, newestMtime(path3.join(p, name), childStats));
564
+ const childStats = lstatSync(path5.join(p, name));
565
+ newest = Math.max(newest, newestMtime(path5.join(p, name), childStats));
566
566
  } catch {}
567
567
  }
568
568
  return newest;
@@ -615,7 +615,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
615
615
  return;
616
616
  }
617
617
  const freshCutoff = Date.now() - PRUNE_FRESH_MS;
618
- const entries3 = BUDGETED_CACHE_DIRS.flatMap((name) => collectCacheEntries(path3.join(CACHE_ROOT, name)));
618
+ const entries3 = BUDGETED_CACHE_DIRS.flatMap((name) => collectCacheEntries(path5.join(CACHE_ROOT, name)));
619
619
  let total = entries3.reduce((sum3, entry) => sum3 + entry.size, 0);
620
620
  if (total <= budgetBytes) {
621
621
  process.stdout.write(`prune: ${formatBytes(total)} within budget ${formatBytes(budgetBytes)} — nothing to do
@@ -647,7 +647,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
647
647
  throw new BootstrapError(`${GIT_CREDENTIALS_ENV} is not valid base64.`);
648
648
  }
649
649
  JSON.parse(decoded);
650
- mkdirSync(path3.dirname(GIT_CREDENTIALS_FILE), { recursive: true });
650
+ mkdirSync(path5.dirname(GIT_CREDENTIALS_FILE), { recursive: true });
651
651
  const tmp = `${GIT_CREDENTIALS_FILE}.tmp`;
652
652
  writeFileSync(tmp, decoded, { mode: 384 });
653
653
  chmodSync(tmp, 384);
@@ -719,7 +719,7 @@ var init_machine = __esm(() => {
719
719
  CACHE_ROOT = process.env[CACHE_ROOT_ENV] || DEFAULT_CACHE_ROOT;
720
720
  BUDGETED_CACHE_DIRS = ["npm", "bun", "pip"];
721
721
  PRUNE_FRESH_MS = 10 * 60 * 1000;
722
- PRUNE_LOCK = path3.join(CACHE_ROOT, ".prune.lock");
722
+ PRUNE_LOCK = path5.join(CACHE_ROOT, ".prune.lock");
723
723
  STALE_LOCK_MS = 10 * 60 * 1000;
724
724
  USAGE = `Usage: zopu machine <command> (local devices: connect, status, stop, disconnect, start, launchagent — see zopu machine connect --help)
725
725
 
@@ -751,9 +751,9 @@ Commands:
751
751
  });
752
752
 
753
753
  // src/cli.ts
754
- import { chmod as chmod2, lstat as lstat2, mkdir as mkdir4, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
755
- import { homedir as homedir6 } from "node:os";
756
- import path4 from "node:path";
754
+ import { chmod as chmod2, lstat as lstat2, mkdir as mkdir5, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile5 } from "node:fs/promises";
755
+ import { homedir as homedir7 } from "node:os";
756
+ import path6 from "node:path";
757
757
  import { parseArgs } from "node:util";
758
758
 
759
759
  // ../../node_modules/.bun/@durable-streams+client@0.2.5/node_modules/@durable-streams/client/dist/index.js
@@ -4929,31 +4929,14 @@ var normalizeStreamFrame = (item) => {
4929
4929
  }
4930
4930
  return null;
4931
4931
  };
4932
- // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Deferred.js
4933
- var exports_Deferred = {};
4934
- __export(exports_Deferred, {
4935
- sync: () => sync2,
4936
- succeed: () => succeed4,
4937
- poll: () => poll,
4938
- makeUnsafe: () => makeUnsafe2,
4939
- make: () => make6,
4940
- isDoneUnsafe: () => isDoneUnsafe,
4941
- isDone: () => isDone2,
4942
- isDeferred: () => isDeferred,
4943
- into: () => into,
4944
- interruptWith: () => interruptWith,
4945
- interrupt: () => interrupt2,
4946
- failSync: () => failSync2,
4947
- failCauseSync: () => failCauseSync2,
4948
- failCause: () => failCause2,
4949
- fail: () => fail4,
4950
- doneUnsafe: () => doneUnsafe,
4951
- done: () => done2,
4952
- dieSync: () => dieSync,
4953
- die: () => die2,
4954
- completeWith: () => completeWith,
4955
- complete: () => complete,
4956
- await: () => _await
4932
+ // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Data.js
4933
+ var exports_Data = {};
4934
+ __export(exports_Data, {
4935
+ taggedEnum: () => taggedEnum,
4936
+ TaggedError: () => TaggedError2,
4937
+ TaggedClass: () => TaggedClass,
4938
+ Error: () => Error3,
4939
+ Class: () => Class2
4957
4940
  });
4958
4941
 
4959
4942
  // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Pipeable.js
@@ -6145,6 +6128,71 @@ var done = (value2) => {
6145
6128
  return exitFail(Done(value2));
6146
6129
  };
6147
6130
 
6131
+ // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Data.js
6132
+ var Class2 = class extends Class {
6133
+ constructor(props) {
6134
+ super();
6135
+ if (props) {
6136
+ assignProperties(this, props);
6137
+ }
6138
+ }
6139
+ };
6140
+ var TaggedClass = (tag) => class extends Class2 {
6141
+ _tag = tag;
6142
+ };
6143
+ var taggedEnum = () => new Proxy({}, {
6144
+ get(_target, tag, _receiver) {
6145
+ if (tag === "$is") {
6146
+ return isTagged;
6147
+ } else if (tag === "$match") {
6148
+ return taggedMatch;
6149
+ }
6150
+ return (props) => ({
6151
+ ...props,
6152
+ _tag: tag
6153
+ });
6154
+ }
6155
+ });
6156
+ function taggedMatch() {
6157
+ if (arguments.length === 1) {
6158
+ const cases2 = arguments[0];
6159
+ return function(value3) {
6160
+ return cases2[value3._tag](value3);
6161
+ };
6162
+ }
6163
+ const value2 = arguments[0];
6164
+ const cases = arguments[1];
6165
+ return cases[value2._tag](value2);
6166
+ }
6167
+ var Error3 = Error2;
6168
+ var TaggedError2 = TaggedError;
6169
+ // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Deferred.js
6170
+ var exports_Deferred = {};
6171
+ __export(exports_Deferred, {
6172
+ sync: () => sync2,
6173
+ succeed: () => succeed4,
6174
+ poll: () => poll,
6175
+ makeUnsafe: () => makeUnsafe2,
6176
+ make: () => make6,
6177
+ isDoneUnsafe: () => isDoneUnsafe,
6178
+ isDone: () => isDone2,
6179
+ isDeferred: () => isDeferred,
6180
+ into: () => into,
6181
+ interruptWith: () => interruptWith,
6182
+ interrupt: () => interrupt2,
6183
+ failSync: () => failSync2,
6184
+ failCauseSync: () => failCauseSync2,
6185
+ failCause: () => failCause2,
6186
+ fail: () => fail4,
6187
+ doneUnsafe: () => doneUnsafe,
6188
+ done: () => done2,
6189
+ dieSync: () => dieSync,
6190
+ die: () => die2,
6191
+ completeWith: () => completeWith,
6192
+ complete: () => complete,
6193
+ await: () => _await
6194
+ });
6195
+
6148
6196
  // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Equivalence.js
6149
6197
  var make = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
6150
6198
  var isStrictEquivalent = (x, y) => x === y;
@@ -7420,18 +7468,6 @@ var PreventSchedulerYield = /* @__PURE__ */ Reference("effect/Scheduler/PreventS
7420
7468
  defaultValue: () => false
7421
7469
  });
7422
7470
 
7423
- // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/Data.js
7424
- var Class2 = class extends Class {
7425
- constructor(props) {
7426
- super();
7427
- if (props) {
7428
- assignProperties(this, props);
7429
- }
7430
- }
7431
- };
7432
- var Error3 = Error2;
7433
- var TaggedError2 = TaggedError;
7434
-
7435
7471
  // ../../node_modules/.bun/effect@4.0.1/node_modules/effect/dist/encoding/EncodingError.js
7436
7472
  var EncodingErrorTypeId = "~effect/encoding/EncodingError";
7437
7473
 
@@ -13072,7 +13108,7 @@ __export(exports_Schema, {
13072
13108
  TaggedUnion: () => TaggedUnion,
13073
13109
  TaggedStruct: () => TaggedStruct,
13074
13110
  TaggedError: () => TaggedError3,
13075
- TaggedClass: () => TaggedClass,
13111
+ TaggedClass: () => TaggedClass2,
13076
13112
  Symbol: () => Symbol3,
13077
13113
  StructWithRest: () => StructWithRest,
13078
13114
  Struct: () => Struct,
@@ -25720,7 +25756,7 @@ var Class3 = (identifier2) => (schema, annotations) => {
25720
25756
  }
25721
25757
  }));
25722
25758
  };
25723
- var TaggedClass = (identifier2) => {
25759
+ var TaggedClass2 = (identifier2) => {
25724
25760
  return (tagValue, schema, annotations) => {
25725
25761
  const struct2 = isStruct(schema) ? schema.mapFields((fields) => ({
25726
25762
  _tag: tag(tagValue),
@@ -26375,7 +26411,11 @@ ${result3.text.slice(0, 4000)}` : "";
26375
26411
 
26376
26412
  // src/machines.ts
26377
26413
  import { spawn as spawn2 } from "node:child_process";
26414
+ import { appendFileSync as appendFileSync2 } from "node:fs";
26415
+ import { copyFile, mkdir as mkdir4, readFile as readFile3, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
26378
26416
  import { hostname as hostname2, platform as platform2 } from "node:os";
26417
+ import path4 from "node:path";
26418
+ import { setTimeout as pause } from "node:timers/promises";
26379
26419
 
26380
26420
  // ../../packages/machines/src/credential.ts
26381
26421
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
@@ -26766,9 +26806,343 @@ var pair = (input) => exports_Effect.gen(function* pairing() {
26766
26806
  });
26767
26807
  return yield* poll3();
26768
26808
  });
26809
+ // ../../packages/machines/src/service.ts
26810
+ import { execFile } from "node:child_process";
26811
+ import { createHash } from "node:crypto";
26812
+ import { promises as fs } from "node:fs";
26813
+ import { homedir as homedir2, userInfo } from "node:os";
26814
+ import path2 from "node:path";
26815
+ var LAUNCH_AGENTS = "Library/LaunchAgents";
26816
+ var SYSTEMD_USER = ".config/systemd/user";
26817
+ var SERVICE_NAME = "zopu-machines";
26818
+
26819
+ class ServiceCommandError extends exports_Data.TaggedError("ServiceCommandError") {
26820
+ }
26821
+ var serviceLabel = (home) => `${SERVICE_NAME}-${createHash("sha256").update(home).digest("hex").slice(0, 8)}`;
26822
+ var servicePath = (runtime, installerPath) => [
26823
+ ...new Set([
26824
+ path2.dirname(runtime),
26825
+ ...installerPath.split(path2.delimiter),
26826
+ "/opt/homebrew/bin",
26827
+ "/usr/local/bin",
26828
+ "/usr/bin",
26829
+ "/bin",
26830
+ "/usr/sbin",
26831
+ "/sbin"
26832
+ ].filter((directory) => directory !== ""))
26833
+ ].join(path2.delimiter);
26834
+ var systemctl = (args2) => ask("systemctl", ["--user", ...args2]);
26835
+ var schtasks = (args2) => ask("schtasks", args2);
26836
+ var execute = (command, args2) => () => new Promise((resolve3, reject) => {
26837
+ execFile(command, [...args2], { encoding: "utf-8", timeout: 20000 }, (error, stdout, stderr) => {
26838
+ if (error) {
26839
+ const code = typeof error.code === "number" ? error.code : null;
26840
+ reject(new ServiceCommandError({
26841
+ code,
26842
+ command: [command, ...args2].join(" "),
26843
+ stderr: stderr.trim()
26844
+ }));
26845
+ return;
26846
+ }
26847
+ resolve3(`${stdout ?? ""}${stderr ?? ""}`);
26848
+ });
26849
+ });
26850
+ var ask = (command, args2) => exports_Effect.tryPromise({
26851
+ catch: (cause) => cause,
26852
+ try: execute(command, args2)
26853
+ });
26854
+ var attempt = (command, args2) => exports_Effect.ignore(ask(command, args2));
26855
+ var fileExists = (file) => exports_Effect.promise(() => fs.access(file).then(() => true).catch(() => false));
26856
+ var writeFile2 = (file, text) => exports_Effect.tryPromise({
26857
+ catch: (cause) => new ServiceCommandError({ code: null, command: `write ${file}`, stderr: String(cause) }),
26858
+ try: async () => {
26859
+ await fs.mkdir(path2.dirname(file), { recursive: true });
26860
+ await fs.writeFile(file, text, { mode: 384 });
26861
+ }
26862
+ });
26863
+ var removeFile = (file) => exports_Effect.promise(() => fs.rm(file, { force: true }));
26864
+ var xml2 = (value4) => value4.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
26865
+ var renderPlist = (plan) => {
26866
+ const variables = { ...plan.env, HOME: homedir2(), PATH: plan.path };
26867
+ return [
26868
+ '<?xml version="1.0" encoding="UTF-8"?>',
26869
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
26870
+ '<plist version="1.0">',
26871
+ "<dict>",
26872
+ " <key>Label</key>",
26873
+ ` <string>${xml2(plan.label)}</string>`,
26874
+ " <key>ProgramArguments</key>",
26875
+ " <array>",
26876
+ ...plan.program.map((argument) => ` <string>${xml2(argument)}</string>`),
26877
+ " </array>",
26878
+ " <key>EnvironmentVariables</key>",
26879
+ " <dict>",
26880
+ ...Object.entries(variables).flatMap(([key, value4]) => [
26881
+ ` <key>${xml2(key)}</key>`,
26882
+ ` <string>${xml2(value4)}</string>`
26883
+ ]),
26884
+ " </dict>",
26885
+ " <key>WorkingDirectory</key>",
26886
+ ` <string>${xml2(homedir2())}</string>`,
26887
+ " <key>RunAtLoad</key>",
26888
+ " <true/>",
26889
+ " <key>KeepAlive</key>",
26890
+ " <dict>",
26891
+ " <key>SuccessfulExit</key>",
26892
+ " <false/>",
26893
+ " </dict>",
26894
+ " <key>ThrottleInterval</key>",
26895
+ " <integer>5</integer>",
26896
+ " <key>ProcessType</key>",
26897
+ " <string>Interactive</string>",
26898
+ " <key>StandardOutPath</key>",
26899
+ ` <string>${xml2(plan.logFile)}</string>`,
26900
+ " <key>StandardErrorPath</key>",
26901
+ ` <string>${xml2(plan.logFile)}</string>`,
26902
+ "</dict>",
26903
+ "</plist>",
26904
+ ""
26905
+ ].join(`
26906
+ `);
26907
+ };
26908
+ var quoteUnit = (value4) => `"${value4.length}:${value4}"`;
26909
+ var renderUnit = (plan) => [
26910
+ "[Unit]",
26911
+ "Description=Zopu machines — this computer, reachable by your threads",
26912
+ "StartLimitIntervalSec=300",
26913
+ "StartLimitBurst=5",
26914
+ "",
26915
+ "[Service]",
26916
+ "Type=simple",
26917
+ "WorkingDirectory=%h",
26918
+ ...Object.entries(plan.env).map(([key, value4]) => `Environment=${key}=${quoteUnit(value4)}`),
26919
+ `Environment=PATH=${quoteUnit(plan.path)}`,
26920
+ `ExecStart=${plan.program.map(quoteUnit).join(" ")}`,
26921
+ "Restart=on-failure",
26922
+ "RestartSec=5",
26923
+ `StandardOutput=append:${plan.logFile.replaceAll("%", "%%")}`,
26924
+ `StandardError=append:${plan.logFile.replaceAll("%", "%%")}`,
26925
+ "",
26926
+ "[Install]",
26927
+ "WantedBy=default.target",
26928
+ ""
26929
+ ].join(`
26930
+ `);
26931
+ var launchd = (plan) => {
26932
+ const { uid } = userInfo();
26933
+ const target = `gui/${uid}/${plan.label}`;
26934
+ const file = path2.join(homedir2(), LAUNCH_AGENTS, `${plan.label}.plist`);
26935
+ return {
26936
+ file,
26937
+ install: [
26938
+ attempt("launchctl", ["bootout", "--wait", target]),
26939
+ attempt("launchctl", ["enable", target]),
26940
+ exports_Effect.andThen(writeFile2(file, renderPlist(plan)), ask("launchctl", ["bootstrap", `gui/${uid}`, file]))
26941
+ ],
26942
+ status: exports_Effect.gen(function* status() {
26943
+ const installed = yield* fileExists(file);
26944
+ const printed = yield* exports_Effect.result(ask("launchctl", ["print", target]));
26945
+ if (exports_Result.isFailure(printed)) {
26946
+ return { installed, linger: "yes", pid: null, running: false };
26947
+ }
26948
+ return {
26949
+ installed,
26950
+ linger: "yes",
26951
+ pid: Number(/^\s*pid = (?<pid>\d+)$/mu.exec(printed.success)?.groups?.pid ?? 0) || null,
26952
+ running: /^\s*state = running$/mu.test(printed.success)
26953
+ };
26954
+ }),
26955
+ uninstall: [
26956
+ attempt("launchctl", ["bootout", "--wait", target]),
26957
+ exports_Effect.asVoid(removeFile(file))
26958
+ ]
26959
+ };
26960
+ };
26961
+ var systemd = (plan) => {
26962
+ const unit = `${plan.label}.service`;
26963
+ const file = path2.join(homedir2(), SYSTEMD_USER, unit);
26964
+ const linger = exports_Effect.gen(function* linger2() {
26965
+ const shown = yield* exports_Effect.result(ask("loginctl", ["show-user", userInfo().username, "--property=Linger"]));
26966
+ if (exports_Result.isFailure(shown)) {
26967
+ return "unknown";
26968
+ }
26969
+ return /^Linger=yes$/mu.test(shown.success) ? "yes" : "no";
26970
+ });
26971
+ return {
26972
+ file,
26973
+ install: [
26974
+ writeFile2(file, renderUnit(plan)),
26975
+ systemctl(["daemon-reload"]),
26976
+ systemctl(["enable", "--now", unit]),
26977
+ exports_Effect.gen(function* ensureLinger() {
26978
+ if ((yield* linger) === "no") {
26979
+ yield* attempt("loginctl", ["enable-linger", userInfo().username]);
26980
+ }
26981
+ })
26982
+ ],
26983
+ status: exports_Effect.gen(function* status() {
26984
+ const installed = yield* fileExists(file);
26985
+ const active = yield* exports_Effect.result(systemctl(["is-active", unit]));
26986
+ const running = !exports_Result.isFailure(active) && active.success.trim() === "active";
26987
+ let pid = null;
26988
+ if (running) {
26989
+ const main = yield* exports_Effect.result(systemctl(["show", "-p", "MainPID", "--value", unit]));
26990
+ pid = exports_Result.isFailure(main) ? null : Number(main.success.trim()) || null;
26991
+ }
26992
+ return { installed, linger: yield* linger, pid, running };
26993
+ }),
26994
+ uninstall: [
26995
+ attempt("systemctl", ["--user", "disable", "--now", unit]),
26996
+ exports_Effect.andThen(removeFile(file), attempt("systemctl", ["--user", "daemon-reload"]))
26997
+ ]
26998
+ };
26999
+ };
27000
+ var writeUtf16 = (file, text) => exports_Effect.tryPromise({
27001
+ catch: (cause) => new ServiceCommandError({ code: null, command: `write ${file}`, stderr: String(cause) }),
27002
+ try: async () => {
27003
+ await fs.mkdir(path2.dirname(file), { recursive: true });
27004
+ await fs.writeFile(file, Buffer.concat([Buffer.from([255, 254]), Buffer.from(text, "utf16le")]));
27005
+ }
27006
+ });
27007
+ var vbs = (value4) => value4.replaceAll('"', '""');
27008
+ var renderLauncher = (plan, options) => [
27009
+ "' Zopu machines: the satellite, hidden. Written by `getzopu machines connect`; edited by nothing.",
27010
+ 'Set sh = CreateObject("WScript.Shell")',
27011
+ 'Set env = sh.Environment("PROCESS")',
27012
+ `env("PATH") = "${vbs(plan.path)}"`,
27013
+ `env("ZOPU_MACHINE_LOG") = "${vbs(options.logFile)}"`,
27014
+ ...Object.entries(plan.env).map(([key, value4]) => `env("${vbs(key)}") = "${vbs(value4)}"`),
27015
+ `code = sh.Run("${vbs(plan.program.map((word) => `"${word}"`).join(" "))}", 0, True)`,
27016
+ "WScript.Quit code",
27017
+ ""
27018
+ ].join(`\r
27019
+ `);
27020
+ var renderTask = (options) => {
27021
+ const wscript = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\wscript.exe`;
27022
+ return [
27023
+ '<?xml version="1.0" encoding="UTF-16"?>',
27024
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
27025
+ " <RegistrationInfo>",
27026
+ " <Description>Zopu machines — this computer, reachable by your threads</Description>",
27027
+ " </RegistrationInfo>",
27028
+ " <Triggers>",
27029
+ " <LogonTrigger>",
27030
+ " <Enabled>true</Enabled>",
27031
+ ` <UserId>${xml2(options.user)}</UserId>`,
27032
+ " </LogonTrigger>",
27033
+ " </Triggers>",
27034
+ " <Principals>",
27035
+ ' <Principal id="Author">',
27036
+ ` <UserId>${xml2(options.user)}</UserId>`,
27037
+ " <LogonType>InteractiveToken</LogonType>",
27038
+ " <RunLevel>LeastPrivilege</RunLevel>",
27039
+ " </Principal>",
27040
+ " </Principals>",
27041
+ " <Settings>",
27042
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
27043
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
27044
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
27045
+ " <AllowHardTerminate>true</AllowHardTerminate>",
27046
+ " <StartWhenAvailable>true</StartWhenAvailable>",
27047
+ " <Hidden>true</Hidden>",
27048
+ " <Enabled>true</Enabled>",
27049
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>",
27050
+ " <RestartOnFailure>",
27051
+ " <Interval>PT1M</Interval>",
27052
+ " <Count>999</Count>",
27053
+ " </RestartOnFailure>",
27054
+ " </Settings>",
27055
+ ' <Actions Context="Author">',
27056
+ " <Exec>",
27057
+ ` <Command>${xml2(wscript)}</Command>`,
27058
+ ` <Arguments>//B &quot;${xml2(options.launcher)}&quot;</Arguments>`,
27059
+ " </Exec>",
27060
+ " </Actions>",
27061
+ "</Task>",
27062
+ ""
27063
+ ].join(`\r
27064
+ `);
27065
+ };
27066
+ var windows = (plan) => {
27067
+ const name = plan.label;
27068
+ const taskFile = path2.join(plan.home, "zopu-machines.task.xml");
27069
+ const launcher = path2.join(plan.home, "zopu-machines.vbs");
27070
+ const state = () => ask("powershell", [
27071
+ "-NoProfile",
27072
+ "-NonInteractive",
27073
+ "-Command",
27074
+ `(Get-ScheduledTask -TaskName '${name.replaceAll("'", "''")}' -ErrorAction SilentlyContinue).State`
27075
+ ]);
27076
+ const user = process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${process.env.USERNAME ?? userInfo().username}` : process.env.USERNAME ?? userInfo().username;
27077
+ return {
27078
+ file: taskFile,
27079
+ install: [
27080
+ writeFile2(launcher, renderLauncher(plan, { logFile: plan.logFile })),
27081
+ writeUtf16(taskFile, renderTask({ launcher, user })),
27082
+ schtasks(["/Create", "/TN", name, "/XML", taskFile, "/F"]),
27083
+ schtasks(["/Run", "/TN", name])
27084
+ ],
27085
+ status: exports_Effect.gen(function* status() {
27086
+ const installed = yield* fileExists(taskFile);
27087
+ const shown = yield* exports_Effect.result(state());
27088
+ const running = !exports_Result.isFailure(shown) && /\bRunning\b/u.test(shown.success);
27089
+ let pid = null;
27090
+ if (running) {
27091
+ const held = yield* exports_Effect.result(exports_Effect.promise(() => fs.readFile(path2.join(plan.home, "state.json"), "utf-8")));
27092
+ if (!exports_Result.isFailure(held)) {
27093
+ const parsed = JSON.parse(held.success);
27094
+ pid = typeof parsed.pid === "number" ? parsed.pid : null;
27095
+ }
27096
+ }
27097
+ return { installed, linger: "yes", pid, running };
27098
+ }),
27099
+ uninstall: [
27100
+ attempt("schtasks", ["/End", "/TN", name]),
27101
+ attempt("schtasks", ["/Delete", "/TN", name, "/F"]),
27102
+ exports_Effect.asVoid(removeFile(taskFile)),
27103
+ exports_Effect.asVoid(removeFile(launcher))
27104
+ ]
27105
+ };
27106
+ };
27107
+ var serviceManager = (plan, platform = process.platform) => {
27108
+ if (platform === "darwin") {
27109
+ return exports_Effect.succeed(launchd(plan));
27110
+ }
27111
+ if (platform === "linux") {
27112
+ return exports_Effect.succeed(systemd(plan));
27113
+ }
27114
+ if (platform === "win32") {
27115
+ return exports_Effect.succeed(windows(plan));
27116
+ }
27117
+ return exports_Effect.fail(new ServiceCommandError({
27118
+ code: null,
27119
+ command: "install the background service",
27120
+ stderr: "The background service is available on macOS, Linux and Windows; on other systems run connect with --foreground."
27121
+ }));
27122
+ };
27123
+ var installService = (plan, platform) => exports_Effect.gen(function* install() {
27124
+ const manager = yield* serviceManager(plan, platform);
27125
+ for (const step of manager.install) {
27126
+ yield* step;
27127
+ }
27128
+ return yield* manager.status;
27129
+ });
27130
+ var uninstallService = (plan, platform) => exports_Effect.gen(function* uninstall() {
27131
+ const manager = yield* serviceManager(plan, platform);
27132
+ for (const step of manager.uninstall) {
27133
+ yield* step;
27134
+ }
27135
+ });
27136
+ var serviceStatus = (plan, platform) => exports_Effect.gen(function* status() {
27137
+ const manager = yield* exports_Effect.result(serviceManager(plan, platform));
27138
+ if (exports_Result.isFailure(manager)) {
27139
+ return { installed: false, linger: "yes", pid: null, running: false };
27140
+ }
27141
+ return yield* manager.success.status;
27142
+ });
26769
27143
  // ../../packages/machines/src/satellite/commands.ts
26770
- import { spawn } from "node:child_process";
26771
- import { homedir as homedir2 } from "node:os";
27144
+ import { spawn, spawnSync } from "node:child_process";
27145
+ import { homedir as homedir3 } from "node:os";
26772
27146
  import { StringDecoder } from "node:string_decoder";
26773
27147
  var BATCH_MS = 50;
26774
27148
  var NO_END = {
@@ -26812,10 +27186,19 @@ var flushAllOutput = (command, writer) => {
26812
27186
  }
26813
27187
  };
26814
27188
  var signalCommand = (child, signal) => {
26815
- const group = child.pid === undefined ? undefined : child.pid * -1;
26816
- if (group === undefined) {
27189
+ if (child.pid === undefined) {
26817
27190
  return;
26818
27191
  }
27192
+ if (process.platform === "win32") {
27193
+ try {
27194
+ spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
27195
+ stdio: "ignore",
27196
+ windowsHide: true
27197
+ });
27198
+ } catch {}
27199
+ return;
27200
+ }
27201
+ const group = child.pid * -1;
26819
27202
  try {
26820
27203
  process.kill(group, signal);
26821
27204
  } catch {}
@@ -26901,11 +27284,12 @@ class Commands {
26901
27284
  let child;
26902
27285
  try {
26903
27286
  child = spawn(request3.command, {
26904
- cwd: request3.cwd ?? homedir2(),
27287
+ cwd: request3.cwd ?? homedir3(),
26905
27288
  detached: true,
26906
27289
  env: { ...process.env, ...request3.env },
26907
27290
  shell: true,
26908
- stdio: ["ignore", "pipe", "pipe"]
27291
+ stdio: ["ignore", "pipe", "pipe"],
27292
+ windowsHide: true
26909
27293
  });
26910
27294
  } catch (error) {
26911
27295
  const message = error instanceof Error ? error.message : "Could not start.";
@@ -27047,14 +27431,14 @@ class Commands {
27047
27431
  var tailOf = (lines, stream2) => lines.filter((line2) => line2.type === "out" && line2.stream === stream2).map((line2) => line2.type === "out" ? line2.data : "").join("").slice(-MACHINE_OUTPUT_MAX_BYTES);
27048
27432
 
27049
27433
  // ../../packages/machines/src/satellite/journal.ts
27050
- import { createHash } from "node:crypto";
27434
+ import { createHash as createHash2 } from "node:crypto";
27051
27435
  import { appendFileSync, createWriteStream } from "node:fs";
27052
27436
  import { mkdir as mkdir2, readdir, readFile as readFile2, stat, unlink } from "node:fs/promises";
27053
- import path2 from "node:path";
27437
+ import path3 from "node:path";
27054
27438
  var FILE_MAX_BYTES = 4 * 1024 * 1024;
27055
27439
  var KEEP_COMMANDS = 200;
27056
27440
  var KEEP_MS = 24 * 60 * 60000;
27057
- var fileName = (id2) => `${createHash("sha256").update(id2).digest("hex").slice(0, 40)}.jsonl`;
27441
+ var fileName = (id2) => `${createHash2("sha256").update(id2).digest("hex").slice(0, 40)}.jsonl`;
27058
27442
  var parse2 = (text) => {
27059
27443
  const lines = [];
27060
27444
  for (const line2 of text.split(`
@@ -27071,12 +27455,12 @@ var parse2 = (text) => {
27071
27455
  var makeJournal = (dir) => ({
27072
27456
  lost: (id2) => {
27073
27457
  try {
27074
- appendFileSync(path2.join(dir, fileName(id2)), `${JSON.stringify({ type: "lost" })}
27458
+ appendFileSync(path3.join(dir, fileName(id2)), `${JSON.stringify({ type: "lost" })}
27075
27459
  `);
27076
27460
  } catch {}
27077
27461
  },
27078
27462
  open: (id2, meta) => {
27079
- let stream2 = createWriteStream(path2.join(dir, fileName(id2)), {
27463
+ let stream2 = createWriteStream(path3.join(dir, fileName(id2)), {
27080
27464
  flags: "a"
27081
27465
  });
27082
27466
  const write2 = (line2) => {
@@ -27104,7 +27488,7 @@ var makeJournal = (dir) => ({
27104
27488
  const now2 = Date.now();
27105
27489
  const entries3 = await readdir(dir).catch(() => []);
27106
27490
  const dated = await Promise.all(entries3.map(async (name) => {
27107
- const file = path2.join(dir, name);
27491
+ const file = path3.join(dir, name);
27108
27492
  const mtimeMs = await stat(file).then((info) => info.mtimeMs).catch(() => 0);
27109
27493
  return { file, mtimeMs };
27110
27494
  }));
@@ -27118,7 +27502,7 @@ var makeJournal = (dir) => ({
27118
27502
  },
27119
27503
  read: async (id2) => {
27120
27504
  try {
27121
- return parse2(await readFile2(path2.join(dir, fileName(id2)), "utf-8"));
27505
+ return parse2(await readFile2(path3.join(dir, fileName(id2)), "utf-8"));
27122
27506
  } catch {
27123
27507
  return [];
27124
27508
  }
@@ -27129,11 +27513,11 @@ var ensureJournalDir = async (dir) => {
27129
27513
  };
27130
27514
 
27131
27515
  // ../../packages/machines/src/satellite/session.ts
27132
- import { homedir as homedir4, hostname, platform } from "node:os";
27516
+ import { homedir as homedir5, hostname, platform } from "node:os";
27133
27517
 
27134
27518
  // ../../packages/machines/src/satellite/files.ts
27135
- import { lstat, mkdir as mkdir3, open, readdir as readdir2, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
27136
- import { homedir as homedir3 } from "node:os";
27519
+ import { lstat, mkdir as mkdir3, open, readdir as readdir2, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
27520
+ import { homedir as homedir4 } from "node:os";
27137
27521
  import nodePath from "node:path";
27138
27522
  var taggedError3 = exports_Schema.TaggedError;
27139
27523
 
@@ -27152,7 +27536,7 @@ var codeOf2 = (cause) => {
27152
27536
  }
27153
27537
  return "unknown";
27154
27538
  };
27155
- var fs = (run2) => exports_Effect.tryPromise({
27539
+ var fs2 = (run2) => exports_Effect.tryPromise({
27156
27540
  catch: (cause) => new MachineFailure({
27157
27541
  code: codeOf2(cause),
27158
27542
  message: cause instanceof Error ? cause.message : String(cause)
@@ -27161,21 +27545,21 @@ var fs = (run2) => exports_Effect.tryPromise({
27161
27545
  });
27162
27546
  var expand = (target) => {
27163
27547
  if (target === "~") {
27164
- return homedir3();
27548
+ return homedir4();
27165
27549
  }
27166
- if (target.startsWith("~/")) {
27167
- return nodePath.join(homedir3(), target.slice(2));
27550
+ if (target.startsWith("~/") || target.startsWith("~\\")) {
27551
+ return nodePath.join(homedir4(), target.slice(2));
27168
27552
  }
27169
27553
  return target;
27170
27554
  };
27171
- var read = (path3) => exports_Effect.gen(function* readFile3() {
27172
- const handle = yield* fs(() => open(expand(path3), "r"));
27555
+ var read = (path4) => exports_Effect.gen(function* readFile3() {
27556
+ const handle = yield* fs2(() => open(expand(path4), "r"));
27173
27557
  const content = yield* exports_Effect.gen(function* body() {
27174
- const { size: size7 } = yield* fs(() => handle.stat());
27558
+ const { size: size7 } = yield* fs2(() => handle.stat());
27175
27559
  const bytes2 = Math.min(size7, MACHINE_READ_MAX_BYTES);
27176
27560
  const buffer = Buffer.alloc(bytes2);
27177
27561
  if (bytes2 > 0) {
27178
- yield* fs(() => handle.read(buffer, 0, bytes2, 0));
27562
+ yield* fs2(() => handle.read(buffer, 0, bytes2, 0));
27179
27563
  }
27180
27564
  return {
27181
27565
  base64: buffer.toString("base64"),
@@ -27185,11 +27569,11 @@ var read = (path3) => exports_Effect.gen(function* readFile3() {
27185
27569
  });
27186
27570
  return yield* exports_Effect.sync(() => content).pipe(exports_Effect.ensuring(exports_Effect.promise(() => handle.close())));
27187
27571
  });
27188
- var write2 = (path3, content) => exports_Effect.map(fs(() => writeFile2(expand(path3), content)), () => ({ bytes: Buffer.byteLength(content) }));
27189
- var makeDir = (path3) => exports_Effect.asVoid(fs(() => mkdir3(expand(path3), { recursive: true })));
27190
- var statOf = (path3) => exports_Effect.gen(function* statPath() {
27191
- const own = yield* fs(() => lstat(expand(path3)));
27192
- const info = own.isSymbolicLink() ? yield* fs(() => stat2(expand(path3))) : own;
27572
+ var write2 = (path4, content) => exports_Effect.map(fs2(() => writeFile3(expand(path4), content)), () => ({ bytes: Buffer.byteLength(content) }));
27573
+ var makeDir = (path4) => exports_Effect.asVoid(fs2(() => mkdir3(expand(path4), { recursive: true })));
27574
+ var statOf = (path4) => exports_Effect.gen(function* statPath() {
27575
+ const own = yield* fs2(() => lstat(expand(path4)));
27576
+ const info = own.isSymbolicLink() ? yield* fs2(() => stat2(expand(path4))) : own;
27193
27577
  return {
27194
27578
  isDirectory: info.isDirectory(),
27195
27579
  isSymbolicLink: own.isSymbolicLink(),
@@ -27197,8 +27581,8 @@ var statOf = (path3) => exports_Effect.gen(function* statPath() {
27197
27581
  size: info.size
27198
27582
  };
27199
27583
  });
27200
- var readDir = (path3) => exports_Effect.map(fs(() => readdir2(expand(path3))), (names) => ({ names }));
27201
- var exists = (path3) => exports_Effect.as(fs(() => stat2(expand(path3))), { exists: true }).pipe(exports_Effect.catchTag("MachineFailure", (failure) => failure.code === "not_found" ? exports_Effect.succeed({ exists: false }) : exports_Effect.fail(failure)));
27584
+ var readDir = (path4) => exports_Effect.map(fs2(() => readdir2(expand(path4))), (names) => ({ names }));
27585
+ var exists = (path4) => exports_Effect.as(fs2(() => stat2(expand(path4))), { exists: true }).pipe(exports_Effect.catchTag("MachineFailure", (failure) => failure.code === "not_found" ? exports_Effect.succeed({ exists: false }) : exports_Effect.fail(failure)));
27202
27586
  var fileOperations = {
27203
27587
  exists,
27204
27588
  mkdir: makeDir,
@@ -27218,7 +27602,7 @@ var decodeFrame = exports_Schema.decodeUnknownResult(MachineFrame);
27218
27602
  var hello = () => ({
27219
27603
  protocol: MACHINE_PROTOCOL_VERSION,
27220
27604
  satellite: {
27221
- home: homedir4(),
27605
+ home: homedir5(),
27222
27606
  hostname: hostname(),
27223
27607
  platform: platform(),
27224
27608
  version: SATELLITE_VERSION
@@ -27450,7 +27834,7 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27450
27834
  exports_Deferred.doneUnsafe(stopped, exports_Effect.succeed(true));
27451
27835
  }, { once: true });
27452
27836
  const headers = { authorization: `Bearer ${options.credential}` };
27453
- const attempt = () => exports_Effect.scoped(exports_Effect.gen(function* once2() {
27837
+ const attempt2 = () => exports_Effect.scoped(exports_Effect.gen(function* once2() {
27454
27838
  const opened = yield* exports_Effect.result(connect(url, headers));
27455
27839
  if (exports_Result.isFailure(opened)) {
27456
27840
  const { code, message } = opened.failure;
@@ -27467,8 +27851,10 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27467
27851
  }
27468
27852
  current = connection;
27469
27853
  options.log(`Connected to Zopu as “${options.name}”.`);
27854
+ options.state?.(true);
27470
27855
  const closed = yield* runSession(connection, commands, options.log);
27471
27856
  current = null;
27857
+ options.state?.(false);
27472
27858
  if (yield* exports_Deferred.isDone(stopped)) {
27473
27859
  return { kind: "stopped" };
27474
27860
  }
@@ -27476,7 +27862,7 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27476
27862
  }));
27477
27863
  const loop = (failures) => exports_Effect.gen(function* retry3() {
27478
27864
  const openedAt = Date.now();
27479
- const outcome = yield* attempt();
27865
+ const outcome = yield* attempt2();
27480
27866
  if (outcome.kind === "stopped") {
27481
27867
  return "stopped";
27482
27868
  }
@@ -27500,39 +27886,55 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27500
27886
  yield* exports_Effect.raceFirst(exports_Effect.sleep(wait), exports_Deferred.await(stopped));
27501
27887
  return yield* loop(next);
27502
27888
  });
27503
- return yield* loop(0).pipe(exports_Effect.ensuring(exports_Effect.sync(() => commands.shutdown())));
27889
+ return yield* loop(0).pipe(exports_Effect.ensuring(exports_Effect.sync(() => {
27890
+ commands.shutdown();
27891
+ options.state?.(false);
27892
+ })));
27504
27893
  });
27505
27894
  // src/machines.ts
27506
- var usage = `Usage: getzopu machines connect [--name <name>] [--url <url>]
27895
+ var usage = `Usage: getzopu machines connect [--name <name>] [--url <url>] [--foreground]
27507
27896
  getzopu machines status
27508
27897
  getzopu machines disconnect
27509
27898
 
27510
27899
  connect Connect this computer to your Zopu account and keep it
27511
- connected. Zopu opens a page to sign in to and prints a code to
27512
- type there; the credential then stays in a file only you can
27513
- read. Ctrl-C stops it. A computer that is already connected
27514
- connects again.
27515
- --name <name> What Zopu calls this computer
27516
- --url <url> Zopu's address (default https://zopu.live,
27517
- ZOPU_URL honoured)
27518
- status Whether this computer is connected, and to which Zopu.
27519
- disconnect Disconnect this computer from Zopu and forget the credential.
27900
+ connected. Zopu opens a page to sign in to and prints a code to
27901
+ type there; the credential then stays in a file only you can
27902
+ read. The connection then runs as a service of your account —
27903
+ it starts when you sign in and reconnects on its own — so this
27904
+ window can close. A computer that is already connected connects
27905
+ again (and takes a newer version of the program).
27906
+ --name <name> What Zopu calls this computer
27907
+ --url <url> Zopu's address (default https://zopu.live,
27908
+ ZOPU_URL honoured)
27909
+ --foreground Run the connection in this terminal instead
27910
+ (Ctrl-C stops it)
27911
+ status Whether this computer is connected, how the service is, and
27912
+ the last lines of its log.
27913
+ disconnect Stop the service, disconnect this computer from Zopu, and
27914
+ forget the credential.
27520
27915
  `;
27521
27916
  var parseFlags = (args2) => {
27522
27917
  const flags = {};
27523
27918
  for (let index2 = 0;index2 < args2.length; index2 += 1) {
27524
27919
  const arg = args2[index2] ?? "";
27525
- const takes = arg === "--name" || arg === "--url";
27526
- if (takes) {
27920
+ if (arg === "--foreground") {
27921
+ flags.foreground = true;
27922
+ continue;
27923
+ }
27924
+ if (arg === "--service") {
27925
+ flags.service = true;
27926
+ continue;
27927
+ }
27928
+ if (arg === "--name" || arg === "--url") {
27527
27929
  const value4 = args2[index2 + 1];
27528
27930
  if (!value4) {
27529
27931
  throw new Error(`${arg} requires a value.`);
27530
27932
  }
27531
27933
  flags[arg.slice(2)] = value4;
27532
27934
  index2 += 1;
27533
- } else {
27534
- throw new Error(`Unknown option: ${arg}`);
27935
+ continue;
27535
27936
  }
27937
+ throw new Error(`Unknown option: ${arg}`);
27536
27938
  }
27537
27939
  return flags;
27538
27940
  };
@@ -27545,9 +27947,24 @@ var serverUrl = (override) => {
27545
27947
  return parsed.origin;
27546
27948
  };
27547
27949
  var openBrowser = (url) => {
27548
- const [command, args2] = platform2() === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
27950
+ const here = platform2();
27951
+ let command = "xdg-open";
27952
+ let args2 = [url];
27953
+ if (here === "darwin") {
27954
+ command = "open";
27955
+ }
27956
+ if (here === "win32") {
27957
+ command = "rundll32";
27958
+ args2 = ["url.dll,FileProtocolHandler", url];
27959
+ }
27549
27960
  try {
27550
- spawn2(command, args2, { detached: true, stdio: "ignore" }).unref();
27961
+ const opened = spawn2(command, args2, {
27962
+ detached: true,
27963
+ stdio: "ignore",
27964
+ windowsHide: true
27965
+ });
27966
+ opened.on("error", () => null);
27967
+ opened.unref();
27551
27968
  } catch {}
27552
27969
  };
27553
27970
  var refusal = (reason, url) => {
@@ -27602,7 +28019,7 @@ Waiting for it to be approved…
27602
28019
  serverUrl: paired.serverUrl,
27603
28020
  storedAt: Date.now()
27604
28021
  }));
27605
- console.log(`Connected. The credential is kept in ${file}, readable by you alone.
28022
+ console.log(`Paired. The credential is kept in ${file}, readable by you alone.
27606
28023
  `);
27607
28024
  } catch (error) {
27608
28025
  throw new Error(error instanceof PairingRefused ? refusal(error.reason, url) : "Zopu could not connect this computer. Try again in a moment.", { cause: error });
@@ -27610,53 +28027,217 @@ Waiting for it to be approved…
27610
28027
  process.off("SIGINT", stop);
27611
28028
  }
27612
28029
  };
27613
- var connect2 = async (flags) => {
27614
- const url = serverUrl(flags.url);
27615
- const stored = await exports_Effect.runPromise(loadCredential());
27616
- if (stored && flags.url && new URL(stored.serverUrl).origin !== url) {
27617
- throw new Error(`This computer is already connected to ${new URL(stored.serverUrl).origin}. Run getzopu machines disconnect first.`);
28030
+ var HOME = machineHome();
28031
+ var STATE_FILE = path4.join(HOME, "state.json");
28032
+ var PLAN_FILE = path4.join(HOME, "service.json");
28033
+ var writeState = async (link2) => {
28034
+ await mkdir4(HOME, { recursive: true });
28035
+ const state = { at: Date.now(), link: link2, pid: process.pid };
28036
+ await writeFile4(STATE_FILE, JSON.stringify(state));
28037
+ };
28038
+ var SERVICE_LOG = process.env.ZOPU_MACHINE_LOG;
28039
+ var say = (line2) => {
28040
+ console.log(line2);
28041
+ if (SERVICE_LOG) {
28042
+ appendFileSync2(SERVICE_LOG, `${line2}
28043
+ `);
27618
28044
  }
27619
- const name = flags.name ?? `${hostname2()} (${platform2()})`;
27620
- if (!stored) {
27621
- await pairIfNeeded(url, name);
28045
+ };
28046
+ var readState = async () => {
28047
+ try {
28048
+ return JSON.parse(await readFile3(STATE_FILE, "utf-8"));
28049
+ } catch {
28050
+ return null;
28051
+ }
28052
+ };
28053
+ var readPlan = async () => {
28054
+ try {
28055
+ return JSON.parse(await readFile3(PLAN_FILE, "utf-8"));
28056
+ } catch {
28057
+ return null;
28058
+ }
28059
+ };
28060
+ var logTail = async (file, lines = 6) => {
28061
+ try {
28062
+ const text = await readFile3(file, "utf-8");
28063
+ return text.split(`
28064
+ `).filter((line2) => line2.trim() !== "").slice(-lines);
28065
+ } catch {
28066
+ return [];
27622
28067
  }
28068
+ };
28069
+ var run2 = async () => {
27623
28070
  const credential2 = await exports_Effect.runPromise(loadCredential());
27624
28071
  if (!credential2) {
27625
- throw new Error("Zopu could not connect this computer. Try again in a moment.");
28072
+ return "stopped";
27626
28073
  }
27627
- console.log("This computer is connected to Zopu. Ctrl-C stops it.");
28074
+ console.log("This computer is connected to Zopu.");
27628
28075
  const controller = new AbortController;
27629
28076
  const stop = () => controller.abort();
27630
28077
  process.once("SIGINT", stop);
27631
28078
  process.once("SIGTERM", stop);
27632
- let stopped = false;
27633
28079
  try {
27634
28080
  const end2 = await exports_Effect.runPromise(runSatellite({
27635
28081
  credential: credential2.credential,
27636
28082
  journalDir: journalDir(),
27637
- log: (line2) => console.log(line2),
27638
- name: credential2.name || name,
28083
+ log: say,
28084
+ name: credential2.name || `${hostname2()} (${platform2()})`,
27639
28085
  serverUrl: credential2.serverUrl,
27640
- signal: controller.signal
28086
+ signal: controller.signal,
28087
+ state: (connected) => {
28088
+ writeState(connected ? "connected" : "disconnected").catch(() => null);
28089
+ }
27641
28090
  }));
27642
- stopped = end2 === "stopped";
27643
28091
  if (end2 === "revoked") {
27644
28092
  await exports_Effect.runPromise(forgetCredential());
27645
- process.exitCode = 1;
28093
+ return "revoked";
27646
28094
  }
27647
28095
  } finally {
27648
28096
  process.off("SIGINT", stop);
27649
28097
  process.off("SIGTERM", stop);
28098
+ await writeState("disconnected").catch(() => null);
28099
+ }
28100
+ return "stopped";
28101
+ };
28102
+ var bundlePath = async () => {
28103
+ const file = import.meta.filename ?? "";
28104
+ if (path4.basename(file) !== "getzopu.mjs" || path4.basename(path4.dirname(file)) !== "dist") {
28105
+ throw new Error("The background service needs the published program (npx getzopu …). Run with --foreground from a source checkout.");
27650
28106
  }
27651
- if (stopped) {
28107
+ await stat3(file);
28108
+ return file;
28109
+ };
28110
+ var planService = async () => {
28111
+ const bundle = await bundlePath();
28112
+ const copy3 = path4.join(HOME, "getzopu.mjs");
28113
+ await mkdir4(HOME, { mode: 448, recursive: true });
28114
+ await copyFile(bundle, copy3);
28115
+ const env = {};
28116
+ for (const [key, value4] of Object.entries(process.env)) {
28117
+ if (key.startsWith("ZOPU_MACHINE_") && value4 !== undefined) {
28118
+ env[key] = value4;
28119
+ }
28120
+ }
28121
+ return {
28122
+ env,
28123
+ home: HOME,
28124
+ label: serviceLabel(HOME),
28125
+ logFile: path4.join(HOME, "satellite.log"),
28126
+ path: servicePath(process.execPath, process.env.PATH ?? ""),
28127
+ program: [process.execPath, copy3, "machines", "connect", "--service"]
28128
+ };
28129
+ };
28130
+ var describe = (service4) => {
28131
+ if (service4.running) {
28132
+ return `The service is running (process ${String(service4.pid)}).`;
28133
+ }
28134
+ if (service4.installed) {
28135
+ return "The service is installed, not running.";
28136
+ }
28137
+ return "The service is not installed.";
28138
+ };
28139
+ var LINGER = 'This Linux account\'s services stop when it logs out; `loginctl enable-linger "$(id -un)"` keeps them running.';
28140
+ var awaitLink = async (since, ms) => {
28141
+ const state = await readState();
28142
+ if (state?.link === "connected" && state.at >= since) {
28143
+ return true;
28144
+ }
28145
+ if (Date.now() >= since + ms) {
28146
+ return false;
28147
+ }
28148
+ await pause(500);
28149
+ return awaitLink(since, ms);
28150
+ };
28151
+ var connect2 = async (flags) => {
28152
+ const url = serverUrl(flags.url);
28153
+ const stored = await exports_Effect.runPromise(loadCredential());
28154
+ if (stored && flags.url && new URL(stored.serverUrl).origin !== url) {
28155
+ throw new Error(`This computer is already connected to ${new URL(stored.serverUrl).origin}. Run getzopu machines disconnect first.`);
28156
+ }
28157
+ const name = flags.name ?? `${hostname2()} (${platform2()})`;
28158
+ if (flags.service) {
28159
+ if (!stored) {
28160
+ console.log("This computer has no credential to connect with; nothing to run.");
28161
+ return;
28162
+ }
28163
+ const end2 = await run2();
28164
+ console.log(end2 === "revoked" ? "This computer is disconnected from Zopu; the service will not start it again." : "Stopped.");
28165
+ return;
28166
+ }
28167
+ if (!stored) {
28168
+ await pairIfNeeded(url, name);
28169
+ }
28170
+ const credential2 = await exports_Effect.runPromise(loadCredential());
28171
+ if (!credential2) {
28172
+ throw new Error("Zopu could not connect this computer. Try again in a moment.");
28173
+ }
28174
+ if (flags.foreground) {
28175
+ console.log("This computer is connected to Zopu. Ctrl-C stops it.");
28176
+ const end2 = await run2();
28177
+ if (end2 === "revoked") {
28178
+ process.exitCode = 1;
28179
+ return;
28180
+ }
27652
28181
  console.log("Stopped. This computer is still connected; run getzopu machines connect to connect it again.");
28182
+ return;
27653
28183
  }
28184
+ const since = Date.now();
28185
+ const plan = await planService();
28186
+ const service4 = await exports_Effect.runPromise(installService(plan));
28187
+ await writeFile4(PLAN_FILE, JSON.stringify(plan));
28188
+ const linked = await awaitLink(since, 30000);
28189
+ if (!linked) {
28190
+ const tail = await logTail(plan.logFile);
28191
+ console.log(`Zopu could not confirm the connection in time. ${describe(service4)}
28192
+
28193
+ The last lines of its log (${plan.logFile}):
28194
+ ${tail.map((line2) => ` ${line2}`).join(`
28195
+ `)}`);
28196
+ return;
28197
+ }
28198
+ console.log("Connected. Zopu keeps this computer connected in the background: the connection starts when you sign in and reconnects on its own, so this window can close.");
28199
+ console.log(`
28200
+ ${describe(service4)}${service4.linger === "no" ? ` ${LINGER}` : ""}`);
28201
+ console.log(`
28202
+ getzopu machines status how it is, and the last lines of its log`);
28203
+ console.log(" getzopu machines disconnect stop it and disconnect this computer for good");
28204
+ console.log(`
28205
+ The log is ${plan.logFile}; the credential is kept in ${HOME}, readable by you alone.`);
27654
28206
  };
27655
28207
  var status = async () => {
27656
28208
  const stored = await exports_Effect.runPromise(loadCredential());
27657
- console.log(JSON.stringify(stored ? { connected: true, machineId: stored.machineId, name: stored.name, url: stored.serverUrl } : { connected: false }, null, 2));
28209
+ const plan = await readPlan();
28210
+ const service4 = plan ? await exports_Effect.runPromise(serviceStatus(plan)) : null;
28211
+ const state = await readState();
28212
+ console.log(JSON.stringify({
28213
+ link: state?.link ?? "unknown",
28214
+ machineId: stored?.machineId ?? null,
28215
+ name: stored?.name ?? null,
28216
+ paired: stored !== null,
28217
+ service: service4 ? {
28218
+ installed: service4.installed,
28219
+ linger: service4.linger,
28220
+ pid: service4.pid,
28221
+ running: service4.running
28222
+ } : null,
28223
+ url: stored?.serverUrl ?? null
28224
+ }, null, 2));
28225
+ if (plan) {
28226
+ const tail = await logTail(plan.logFile, 4);
28227
+ if (tail.length > 0) {
28228
+ console.log(`
28229
+ The last lines of its log (${plan.logFile}):`);
28230
+ for (const line2 of tail) {
28231
+ console.log(` ${line2}`);
28232
+ }
28233
+ }
28234
+ }
27658
28235
  };
27659
28236
  var disconnect = async () => {
28237
+ const plan = await readPlan();
28238
+ if (plan) {
28239
+ await exports_Effect.runPromise(exports_Effect.ignore(uninstallService(plan)));
28240
+ }
27660
28241
  const stored = await exports_Effect.runPromise(loadCredential());
27661
28242
  if (!stored) {
27662
28243
  console.log("This computer is not connected to Zopu.");
@@ -27673,7 +28254,7 @@ var disconnect = async () => {
27673
28254
  reached = false;
27674
28255
  }
27675
28256
  await exports_Effect.runPromise(forgetCredential());
27676
- console.log(reached ? "This computer is disconnected from Zopu." : "Zopu could not be reached, so the credential was forgotten here only. Disconnect this computer in Zopu as well.");
28257
+ console.log(reached ? "The service is stopped and removed, and this computer is disconnected from Zopu." : "The service is stopped and removed. Zopu could not be reached, so the credential was forgotten here only. Disconnect this computer in Zopu as well.");
27677
28258
  };
27678
28259
  var runMachines = async (args2) => {
27679
28260
  const [command, ...rest] = args2;
@@ -27729,14 +28310,14 @@ Local development against http://127.0.0.1:3000 also accepts the token
27729
28310
  seeded by bun run dev:db. --json emits JSON; streams emit JSON lines.
27730
28311
  Errors exit nonzero. No token is printed.
27731
28312
  `;
27732
- var configFile = path4.join(process.env.XDG_CONFIG_HOME ?? path4.join(homedir6(), ".config"), "zopu", "config.json");
28313
+ var configFile = path6.join(process.env.XDG_CONFIG_HOME ?? path6.join(homedir7(), ".config"), "zopu", "config.json");
27733
28314
  var readConfig = async () => {
27734
28315
  try {
27735
28316
  const info = await lstat2(configFile);
27736
28317
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 63) !== 0) {
27737
28318
  throw new Error("Zopu auth config must be a private regular file (chmod 600).");
27738
28319
  }
27739
- const value4 = JSON.parse(await readFile3(configFile, "utf-8"));
28320
+ const value4 = JSON.parse(await readFile4(configFile, "utf-8"));
27740
28321
  if (typeof value4 !== "object" || value4 === null) {
27741
28322
  throw new Error("Invalid Zopu auth configuration.");
27742
28323
  }
@@ -27754,8 +28335,8 @@ var readConfig = async () => {
27754
28335
  var LOOPBACK_HOSTS2 = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
27755
28336
  var readDevToken = async () => {
27756
28337
  const candidates = [
27757
- path4.join(process.cwd(), ".dev", "zopu-cli-token"),
27758
- path4.join(path4.resolve(process.cwd(), ".."), ".dev", "zopu-cli-token")
28338
+ path6.join(process.cwd(), ".dev", "zopu-cli-token"),
28339
+ path6.join(path6.resolve(process.cwd(), ".."), ".dev", "zopu-cli-token")
27759
28340
  ];
27760
28341
  for (const candidate of candidates) {
27761
28342
  try {
@@ -27763,7 +28344,7 @@ var readDevToken = async () => {
27763
28344
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 63) !== 0) {
27764
28345
  continue;
27765
28346
  }
27766
- const contents = await readFile3(candidate, "utf-8");
28347
+ const contents = await readFile4(candidate, "utf-8");
27767
28348
  const value4 = contents.trim();
27768
28349
  if (/^zopu_key_[A-Za-z0-9_-]{43}$/u.test(value4)) {
27769
28350
  return value4;
@@ -27866,9 +28447,9 @@ var main = async () => {
27866
28447
  throw new Error("Invalid Zopu API token.");
27867
28448
  }
27868
28449
  await createZopuClient({ baseUrl: url, token: received }).projects.list();
27869
- await mkdir4(path4.dirname(configFile), { mode: 448, recursive: true });
28450
+ await mkdir5(path6.dirname(configFile), { mode: 448, recursive: true });
27870
28451
  const temporary = `${configFile}.${process.pid}.tmp`;
27871
- await writeFile3(temporary, `${JSON.stringify({ token: received, url })}
28452
+ await writeFile5(temporary, `${JSON.stringify({ token: received, url })}
27872
28453
  `, {
27873
28454
  flag: "wx",
27874
28455
  mode: 384
@@ -27921,7 +28502,7 @@ var main = async () => {
27921
28502
  throw new Error("Not signed in. Create a token in Zopu Profile, then use auth login --token-stdin.");
27922
28503
  }
27923
28504
  const client = createZopuClient({ baseUrl: url, token });
27924
- const input = values2.input ? objectInput(values2.input === "-" ? await stdin() : await readFile3(values2.input, "utf-8")) : {};
28505
+ const input = values2.input ? objectInput(values2.input === "-" ? await stdin() : await readFile4(values2.input, "utf-8")) : {};
27925
28506
  if (["delete", "archive"].includes(command ?? "") && !values2.yes) {
27926
28507
  throw new Error("This action requires --yes.");
27927
28508
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "getzopu",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Zopu CLI: projects, threads, and connecting your own computer to Zopu.",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {