getzopu 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +20 -10
  2. package/dist/getzopu.mjs +581 -136
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -59,16 +59,26 @@ 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
+ No root. The service runs a copy of this program kept under `~/.config/zopu/machine/`, with the
69
+ runtime that ran `connect`, and writes to `satellite.log` there; it is restarted only when it
70
+ crashes — a revoked or deliberately stopped satellite stays stopped. The service's name carries a
71
+ hash of the machine's home, so a second Zopu on one computer never displaces the first. The shape
72
+ follows t3 code's background service. `--foreground` runs the satellite in the terminal until Ctrl-C
73
+ instead.
74
+
75
+ The satellite (`packages/machines/src/satellite/`) dials out to `/ws/machines` with the credential
76
+ as a bearer, comes back by itself after a drop (at once the first time, then on a ladder from 1 s
77
+ to 30 s), and keeps a journal of every command it ran (`~/.config/zopu/machine/journal/`), so a
78
+ command that outlives a drop is picked up where it was. Commands run as the user, in a process
79
+ group of their own; nothing is scoped. `getzopu machines status` says whether the link is up, how
80
+ the service is, and the last lines of its log; `getzopu machines disconnect` stops and removes the
81
+ service, revokes the computer on the server, and forgets the credential.
72
82
 
73
83
  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
84
 
package/dist/getzopu.mjs CHANGED
@@ -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
  `);
@@ -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,10 @@ ${result3.text.slice(0, 4000)}` : "";
26375
26411
 
26376
26412
  // src/machines.ts
26377
26413
  import { spawn as spawn2 } from "node:child_process";
26414
+ import { copyFile, mkdir as mkdir4, readFile as readFile3, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
26378
26415
  import { hostname as hostname2, platform as platform2 } from "node:os";
26416
+ import path4 from "node:path";
26417
+ import { setTimeout as pause } from "node:timers/promises";
26379
26418
 
26380
26419
  // ../../packages/machines/src/credential.ts
26381
26420
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
@@ -26610,6 +26649,7 @@ var SatelliteFrame = exports_Schema.Union([
26610
26649
  ]);
26611
26650
  var MachineExecResult = exports_Schema.Struct({
26612
26651
  exitCode: exports_Schema.NullOr(exports_Schema.Number.check(exports_Schema.isInt())),
26652
+ lastSeq: exports_Schema.Number.check(exports_Schema.isInt(), exports_Schema.isGreaterThanOrEqualTo(-1)),
26613
26653
  signal: exports_Schema.NullOr(exports_Schema.String),
26614
26654
  stderr: exports_Schema.String,
26615
26655
  stdout: exports_Schema.String,
@@ -26664,13 +26704,21 @@ var MachinePairPollResult = exports_Schema.Union([
26664
26704
  ]);
26665
26705
  var MachineSummary = exports_Schema.Struct({
26666
26706
  connected: exports_Schema.Boolean,
26707
+ home: exports_Schema.NullOr(exports_Schema.String),
26708
+ hostname: exports_Schema.NullOr(exports_Schema.String),
26667
26709
  id: exports_Schema.String,
26668
26710
  lastSeenAt: exports_Schema.NullOr(exports_Schema.Number.check(exports_Schema.isInt(), exports_Schema.isGreaterThanOrEqualTo(0))),
26669
26711
  name: exports_Schema.String,
26670
26712
  platform: exports_Schema.NullOr(exports_Schema.String)
26671
26713
  });
26672
- var MachineListInput = exports_Schema.Struct({});
26714
+ var MachineListInput = exports_Schema.Struct({
26715
+ ownerId: exports_Schema.String.check(exports_Schema.isMinLength(1), exports_Schema.isMaxLength(128))
26716
+ });
26673
26717
  var MachineListResult = exports_Schema.Struct({ machines: exports_Schema.Array(MachineSummary) });
26718
+ var MachineSelection = exports_Schema.Struct({
26719
+ id: exports_Schema.String.check(exports_Schema.isMinLength(1), exports_Schema.isMaxLength(128)),
26720
+ name: exports_Schema.String
26721
+ });
26674
26722
  var MACHINE_PROTOCOL_VERSION = 1;
26675
26723
 
26676
26724
  // ../../packages/machines/src/pairing.ts
@@ -26757,9 +26805,232 @@ var pair = (input) => exports_Effect.gen(function* pairing() {
26757
26805
  });
26758
26806
  return yield* poll3();
26759
26807
  });
26808
+ // ../../packages/machines/src/service.ts
26809
+ import { execFile } from "node:child_process";
26810
+ import { createHash } from "node:crypto";
26811
+ import { promises as fs } from "node:fs";
26812
+ import { homedir as homedir2, userInfo } from "node:os";
26813
+ import path2 from "node:path";
26814
+ var LAUNCH_AGENTS = "Library/LaunchAgents";
26815
+ var SYSTEMD_USER = ".config/systemd/user";
26816
+ var SERVICE_NAME = "zopu-machines";
26817
+
26818
+ class ServiceCommandError extends exports_Data.TaggedError("ServiceCommandError") {
26819
+ }
26820
+ var serviceLabel = (home) => `${SERVICE_NAME}-${createHash("sha256").update(home).digest("hex").slice(0, 8)}`;
26821
+ var servicePath = (runtime, installerPath) => [
26822
+ ...new Set([
26823
+ path2.dirname(runtime),
26824
+ ...installerPath.split(path2.delimiter),
26825
+ "/opt/homebrew/bin",
26826
+ "/usr/local/bin",
26827
+ "/usr/bin",
26828
+ "/bin",
26829
+ "/usr/sbin",
26830
+ "/sbin"
26831
+ ].filter((directory) => directory !== ""))
26832
+ ].join(path2.delimiter);
26833
+ var systemctl = (args2) => ask("systemctl", ["--user", ...args2]);
26834
+ var execute = (command, args2) => () => new Promise((resolve3, reject) => {
26835
+ execFile(command, [...args2], { encoding: "utf-8", timeout: 20000 }, (error, stdout, stderr) => {
26836
+ if (error) {
26837
+ const code = typeof error.code === "number" ? error.code : null;
26838
+ reject(new ServiceCommandError({
26839
+ code,
26840
+ command: [command, ...args2].join(" "),
26841
+ stderr: stderr.trim()
26842
+ }));
26843
+ return;
26844
+ }
26845
+ resolve3(`${stdout ?? ""}${stderr ?? ""}`);
26846
+ });
26847
+ });
26848
+ var ask = (command, args2) => exports_Effect.tryPromise({
26849
+ catch: (cause) => cause,
26850
+ try: execute(command, args2)
26851
+ });
26852
+ var attempt = (command, args2) => exports_Effect.ignore(ask(command, args2));
26853
+ var fileExists = (file) => exports_Effect.promise(() => fs.access(file).then(() => true).catch(() => false));
26854
+ var writeFile2 = (file, text) => exports_Effect.tryPromise({
26855
+ catch: (cause) => new ServiceCommandError({ code: null, command: `write ${file}`, stderr: String(cause) }),
26856
+ try: async () => {
26857
+ await fs.mkdir(path2.dirname(file), { recursive: true });
26858
+ await fs.writeFile(file, text, { mode: 384 });
26859
+ }
26860
+ });
26861
+ var removeFile = (file) => exports_Effect.promise(() => fs.rm(file, { force: true }));
26862
+ var xml2 = (value4) => value4.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
26863
+ var renderPlist = (plan) => {
26864
+ const variables = { ...plan.env, HOME: homedir2(), PATH: plan.path };
26865
+ return [
26866
+ '<?xml version="1.0" encoding="UTF-8"?>',
26867
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
26868
+ '<plist version="1.0">',
26869
+ "<dict>",
26870
+ " <key>Label</key>",
26871
+ ` <string>${xml2(plan.label)}</string>`,
26872
+ " <key>ProgramArguments</key>",
26873
+ " <array>",
26874
+ ...plan.program.map((argument) => ` <string>${xml2(argument)}</string>`),
26875
+ " </array>",
26876
+ " <key>EnvironmentVariables</key>",
26877
+ " <dict>",
26878
+ ...Object.entries(variables).flatMap(([key, value4]) => [
26879
+ ` <key>${xml2(key)}</key>`,
26880
+ ` <string>${xml2(value4)}</string>`
26881
+ ]),
26882
+ " </dict>",
26883
+ " <key>WorkingDirectory</key>",
26884
+ ` <string>${xml2(homedir2())}</string>`,
26885
+ " <key>RunAtLoad</key>",
26886
+ " <true/>",
26887
+ " <key>KeepAlive</key>",
26888
+ " <dict>",
26889
+ " <key>SuccessfulExit</key>",
26890
+ " <false/>",
26891
+ " </dict>",
26892
+ " <key>ThrottleInterval</key>",
26893
+ " <integer>5</integer>",
26894
+ " <key>ProcessType</key>",
26895
+ " <string>Interactive</string>",
26896
+ " <key>StandardOutPath</key>",
26897
+ ` <string>${xml2(plan.logFile)}</string>`,
26898
+ " <key>StandardErrorPath</key>",
26899
+ ` <string>${xml2(plan.logFile)}</string>`,
26900
+ "</dict>",
26901
+ "</plist>",
26902
+ ""
26903
+ ].join(`
26904
+ `);
26905
+ };
26906
+ var quoteUnit = (value4) => `"${value4.length}:${value4}"`;
26907
+ var renderUnit = (plan) => [
26908
+ "[Unit]",
26909
+ "Description=Zopu machines — this computer, reachable by your threads",
26910
+ "StartLimitIntervalSec=300",
26911
+ "StartLimitBurst=5",
26912
+ "",
26913
+ "[Service]",
26914
+ "Type=simple",
26915
+ "WorkingDirectory=%h",
26916
+ ...Object.entries(plan.env).map(([key, value4]) => `Environment=${key}=${quoteUnit(value4)}`),
26917
+ `Environment=PATH=${quoteUnit(plan.path)}`,
26918
+ `ExecStart=${plan.program.map(quoteUnit).join(" ")}`,
26919
+ "Restart=on-failure",
26920
+ "RestartSec=5",
26921
+ `StandardOutput=append:${plan.logFile.replaceAll("%", "%%")}`,
26922
+ `StandardError=append:${plan.logFile.replaceAll("%", "%%")}`,
26923
+ "",
26924
+ "[Install]",
26925
+ "WantedBy=default.target",
26926
+ ""
26927
+ ].join(`
26928
+ `);
26929
+ var launchd = (plan) => {
26930
+ const { uid } = userInfo();
26931
+ const target = `gui/${uid}/${plan.label}`;
26932
+ const file = path2.join(homedir2(), LAUNCH_AGENTS, `${plan.label}.plist`);
26933
+ return {
26934
+ file,
26935
+ install: [
26936
+ attempt("launchctl", ["bootout", "--wait", target]),
26937
+ attempt("launchctl", ["enable", target]),
26938
+ exports_Effect.andThen(writeFile2(file, renderPlist(plan)), ask("launchctl", ["bootstrap", `gui/${uid}`, file]))
26939
+ ],
26940
+ status: exports_Effect.gen(function* status() {
26941
+ const installed = yield* fileExists(file);
26942
+ const printed = yield* exports_Effect.result(ask("launchctl", ["print", target]));
26943
+ if (exports_Result.isFailure(printed)) {
26944
+ return { installed, linger: "yes", pid: null, running: false };
26945
+ }
26946
+ return {
26947
+ installed,
26948
+ linger: "yes",
26949
+ pid: Number(/^\s*pid = (?<pid>\d+)$/mu.exec(printed.success)?.groups?.pid ?? 0) || null,
26950
+ running: /^\s*state = running$/mu.test(printed.success)
26951
+ };
26952
+ }),
26953
+ uninstall: [
26954
+ attempt("launchctl", ["bootout", "--wait", target]),
26955
+ exports_Effect.asVoid(removeFile(file))
26956
+ ]
26957
+ };
26958
+ };
26959
+ var systemd = (plan) => {
26960
+ const unit = `${plan.label}.service`;
26961
+ const file = path2.join(homedir2(), SYSTEMD_USER, unit);
26962
+ const linger = exports_Effect.gen(function* linger2() {
26963
+ const shown = yield* exports_Effect.result(ask("loginctl", ["show-user", userInfo().username, "--property=Linger"]));
26964
+ if (exports_Result.isFailure(shown)) {
26965
+ return "unknown";
26966
+ }
26967
+ return /^Linger=yes$/mu.test(shown.success) ? "yes" : "no";
26968
+ });
26969
+ return {
26970
+ file,
26971
+ install: [
26972
+ writeFile2(file, renderUnit(plan)),
26973
+ systemctl(["daemon-reload"]),
26974
+ systemctl(["enable", "--now", unit]),
26975
+ exports_Effect.gen(function* ensureLinger() {
26976
+ if ((yield* linger) === "no") {
26977
+ yield* attempt("loginctl", ["enable-linger", userInfo().username]);
26978
+ }
26979
+ })
26980
+ ],
26981
+ status: exports_Effect.gen(function* status() {
26982
+ const installed = yield* fileExists(file);
26983
+ const active = yield* exports_Effect.result(systemctl(["is-active", unit]));
26984
+ const running = !exports_Result.isFailure(active) && active.success.trim() === "active";
26985
+ let pid = null;
26986
+ if (running) {
26987
+ const main = yield* exports_Effect.result(systemctl(["show", "-p", "MainPID", "--value", unit]));
26988
+ pid = exports_Result.isFailure(main) ? null : Number(main.success.trim()) || null;
26989
+ }
26990
+ return { installed, linger: yield* linger, pid, running };
26991
+ }),
26992
+ uninstall: [
26993
+ attempt("systemctl", ["--user", "disable", "--now", unit]),
26994
+ exports_Effect.andThen(removeFile(file), attempt("systemctl", ["--user", "daemon-reload"]))
26995
+ ]
26996
+ };
26997
+ };
26998
+ var serviceManager = (plan, platform = process.platform) => {
26999
+ if (platform === "darwin") {
27000
+ return exports_Effect.succeed(launchd(plan));
27001
+ }
27002
+ if (platform === "linux") {
27003
+ return exports_Effect.succeed(systemd(plan));
27004
+ }
27005
+ return exports_Effect.fail(new ServiceCommandError({
27006
+ code: null,
27007
+ command: "install the background service",
27008
+ stderr: "The background service is available on macOS and Linux; on other systems run connect with --foreground."
27009
+ }));
27010
+ };
27011
+ var installService = (plan, platform) => exports_Effect.gen(function* install() {
27012
+ const manager = yield* serviceManager(plan, platform);
27013
+ for (const step of manager.install) {
27014
+ yield* step;
27015
+ }
27016
+ return yield* manager.status;
27017
+ });
27018
+ var uninstallService = (plan, platform) => exports_Effect.gen(function* uninstall() {
27019
+ const manager = yield* serviceManager(plan, platform);
27020
+ for (const step of manager.uninstall) {
27021
+ yield* step;
27022
+ }
27023
+ });
27024
+ var serviceStatus = (plan, platform) => exports_Effect.gen(function* status() {
27025
+ const manager = yield* exports_Effect.result(serviceManager(plan, platform));
27026
+ if (exports_Result.isFailure(manager)) {
27027
+ return { installed: false, linger: "yes", pid: null, running: false };
27028
+ }
27029
+ return yield* manager.success.status;
27030
+ });
26760
27031
  // ../../packages/machines/src/satellite/commands.ts
26761
27032
  import { spawn } from "node:child_process";
26762
- import { homedir as homedir2 } from "node:os";
27033
+ import { homedir as homedir3 } from "node:os";
26763
27034
  import { StringDecoder } from "node:string_decoder";
26764
27035
  var BATCH_MS = 50;
26765
27036
  var NO_END = {
@@ -26892,7 +27163,7 @@ class Commands {
26892
27163
  let child;
26893
27164
  try {
26894
27165
  child = spawn(request3.command, {
26895
- cwd: request3.cwd ?? homedir2(),
27166
+ cwd: request3.cwd ?? homedir3(),
26896
27167
  detached: true,
26897
27168
  env: { ...process.env, ...request3.env },
26898
27169
  shell: true,
@@ -26956,7 +27227,7 @@ class Commands {
26956
27227
  const command = this.live.get(id2);
26957
27228
  if (command) {
26958
27229
  for (const frame of command.history) {
26959
- if (frame.seq > after) {
27230
+ if (frame.seq >= after) {
26960
27231
  listener(frame);
26961
27232
  }
26962
27233
  }
@@ -27038,14 +27309,14 @@ class Commands {
27038
27309
  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);
27039
27310
 
27040
27311
  // ../../packages/machines/src/satellite/journal.ts
27041
- import { createHash } from "node:crypto";
27312
+ import { createHash as createHash2 } from "node:crypto";
27042
27313
  import { appendFileSync, createWriteStream } from "node:fs";
27043
27314
  import { mkdir as mkdir2, readdir, readFile as readFile2, stat, unlink } from "node:fs/promises";
27044
- import path2 from "node:path";
27315
+ import path3 from "node:path";
27045
27316
  var FILE_MAX_BYTES = 4 * 1024 * 1024;
27046
27317
  var KEEP_COMMANDS = 200;
27047
27318
  var KEEP_MS = 24 * 60 * 60000;
27048
- var fileName = (id2) => `${createHash("sha256").update(id2).digest("hex").slice(0, 40)}.jsonl`;
27319
+ var fileName = (id2) => `${createHash2("sha256").update(id2).digest("hex").slice(0, 40)}.jsonl`;
27049
27320
  var parse2 = (text) => {
27050
27321
  const lines = [];
27051
27322
  for (const line2 of text.split(`
@@ -27062,12 +27333,12 @@ var parse2 = (text) => {
27062
27333
  var makeJournal = (dir) => ({
27063
27334
  lost: (id2) => {
27064
27335
  try {
27065
- appendFileSync(path2.join(dir, fileName(id2)), `${JSON.stringify({ type: "lost" })}
27336
+ appendFileSync(path3.join(dir, fileName(id2)), `${JSON.stringify({ type: "lost" })}
27066
27337
  `);
27067
27338
  } catch {}
27068
27339
  },
27069
27340
  open: (id2, meta) => {
27070
- let stream2 = createWriteStream(path2.join(dir, fileName(id2)), {
27341
+ let stream2 = createWriteStream(path3.join(dir, fileName(id2)), {
27071
27342
  flags: "a"
27072
27343
  });
27073
27344
  const write2 = (line2) => {
@@ -27095,7 +27366,7 @@ var makeJournal = (dir) => ({
27095
27366
  const now2 = Date.now();
27096
27367
  const entries3 = await readdir(dir).catch(() => []);
27097
27368
  const dated = await Promise.all(entries3.map(async (name) => {
27098
- const file = path2.join(dir, name);
27369
+ const file = path3.join(dir, name);
27099
27370
  const mtimeMs = await stat(file).then((info) => info.mtimeMs).catch(() => 0);
27100
27371
  return { file, mtimeMs };
27101
27372
  }));
@@ -27109,7 +27380,7 @@ var makeJournal = (dir) => ({
27109
27380
  },
27110
27381
  read: async (id2) => {
27111
27382
  try {
27112
- return parse2(await readFile2(path2.join(dir, fileName(id2)), "utf-8"));
27383
+ return parse2(await readFile2(path3.join(dir, fileName(id2)), "utf-8"));
27113
27384
  } catch {
27114
27385
  return [];
27115
27386
  }
@@ -27120,11 +27391,11 @@ var ensureJournalDir = async (dir) => {
27120
27391
  };
27121
27392
 
27122
27393
  // ../../packages/machines/src/satellite/session.ts
27123
- import { homedir as homedir4, hostname, platform } from "node:os";
27394
+ import { homedir as homedir5, hostname, platform } from "node:os";
27124
27395
 
27125
27396
  // ../../packages/machines/src/satellite/files.ts
27126
- import { lstat, mkdir as mkdir3, open, readdir as readdir2, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
27127
- import { homedir as homedir3 } from "node:os";
27397
+ import { lstat, mkdir as mkdir3, open, readdir as readdir2, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
27398
+ import { homedir as homedir4 } from "node:os";
27128
27399
  import nodePath from "node:path";
27129
27400
  var taggedError3 = exports_Schema.TaggedError;
27130
27401
 
@@ -27143,7 +27414,7 @@ var codeOf2 = (cause) => {
27143
27414
  }
27144
27415
  return "unknown";
27145
27416
  };
27146
- var fs = (run2) => exports_Effect.tryPromise({
27417
+ var fs2 = (run2) => exports_Effect.tryPromise({
27147
27418
  catch: (cause) => new MachineFailure({
27148
27419
  code: codeOf2(cause),
27149
27420
  message: cause instanceof Error ? cause.message : String(cause)
@@ -27152,21 +27423,21 @@ var fs = (run2) => exports_Effect.tryPromise({
27152
27423
  });
27153
27424
  var expand = (target) => {
27154
27425
  if (target === "~") {
27155
- return homedir3();
27426
+ return homedir4();
27156
27427
  }
27157
27428
  if (target.startsWith("~/")) {
27158
- return nodePath.join(homedir3(), target.slice(2));
27429
+ return nodePath.join(homedir4(), target.slice(2));
27159
27430
  }
27160
27431
  return target;
27161
27432
  };
27162
- var read = (path3) => exports_Effect.gen(function* readFile3() {
27163
- const handle = yield* fs(() => open(expand(path3), "r"));
27433
+ var read = (path4) => exports_Effect.gen(function* readFile3() {
27434
+ const handle = yield* fs2(() => open(expand(path4), "r"));
27164
27435
  const content = yield* exports_Effect.gen(function* body() {
27165
- const { size: size7 } = yield* fs(() => handle.stat());
27436
+ const { size: size7 } = yield* fs2(() => handle.stat());
27166
27437
  const bytes2 = Math.min(size7, MACHINE_READ_MAX_BYTES);
27167
27438
  const buffer = Buffer.alloc(bytes2);
27168
27439
  if (bytes2 > 0) {
27169
- yield* fs(() => handle.read(buffer, 0, bytes2, 0));
27440
+ yield* fs2(() => handle.read(buffer, 0, bytes2, 0));
27170
27441
  }
27171
27442
  return {
27172
27443
  base64: buffer.toString("base64"),
@@ -27176,11 +27447,11 @@ var read = (path3) => exports_Effect.gen(function* readFile3() {
27176
27447
  });
27177
27448
  return yield* exports_Effect.sync(() => content).pipe(exports_Effect.ensuring(exports_Effect.promise(() => handle.close())));
27178
27449
  });
27179
- var write2 = (path3, content) => exports_Effect.map(fs(() => writeFile2(expand(path3), content)), () => ({ bytes: Buffer.byteLength(content) }));
27180
- var makeDir = (path3) => exports_Effect.asVoid(fs(() => mkdir3(expand(path3), { recursive: true })));
27181
- var statOf = (path3) => exports_Effect.gen(function* statPath() {
27182
- const own = yield* fs(() => lstat(expand(path3)));
27183
- const info = own.isSymbolicLink() ? yield* fs(() => stat2(expand(path3))) : own;
27450
+ var write2 = (path4, content) => exports_Effect.map(fs2(() => writeFile3(expand(path4), content)), () => ({ bytes: Buffer.byteLength(content) }));
27451
+ var makeDir = (path4) => exports_Effect.asVoid(fs2(() => mkdir3(expand(path4), { recursive: true })));
27452
+ var statOf = (path4) => exports_Effect.gen(function* statPath() {
27453
+ const own = yield* fs2(() => lstat(expand(path4)));
27454
+ const info = own.isSymbolicLink() ? yield* fs2(() => stat2(expand(path4))) : own;
27184
27455
  return {
27185
27456
  isDirectory: info.isDirectory(),
27186
27457
  isSymbolicLink: own.isSymbolicLink(),
@@ -27188,8 +27459,8 @@ var statOf = (path3) => exports_Effect.gen(function* statPath() {
27188
27459
  size: info.size
27189
27460
  };
27190
27461
  });
27191
- var readDir = (path3) => exports_Effect.map(fs(() => readdir2(expand(path3))), (names) => ({ names }));
27192
- 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)));
27462
+ var readDir = (path4) => exports_Effect.map(fs2(() => readdir2(expand(path4))), (names) => ({ names }));
27463
+ 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)));
27193
27464
  var fileOperations = {
27194
27465
  exists,
27195
27466
  mkdir: makeDir,
@@ -27209,7 +27480,7 @@ var decodeFrame = exports_Schema.decodeUnknownResult(MachineFrame);
27209
27480
  var hello = () => ({
27210
27481
  protocol: MACHINE_PROTOCOL_VERSION,
27211
27482
  satellite: {
27212
- home: homedir4(),
27483
+ home: homedir5(),
27213
27484
  hostname: hostname(),
27214
27485
  platform: platform(),
27215
27486
  version: SATELLITE_VERSION
@@ -27441,7 +27712,7 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27441
27712
  exports_Deferred.doneUnsafe(stopped, exports_Effect.succeed(true));
27442
27713
  }, { once: true });
27443
27714
  const headers = { authorization: `Bearer ${options.credential}` };
27444
- const attempt = () => exports_Effect.scoped(exports_Effect.gen(function* once2() {
27715
+ const attempt2 = () => exports_Effect.scoped(exports_Effect.gen(function* once2() {
27445
27716
  const opened = yield* exports_Effect.result(connect(url, headers));
27446
27717
  if (exports_Result.isFailure(opened)) {
27447
27718
  const { code, message } = opened.failure;
@@ -27458,8 +27729,10 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27458
27729
  }
27459
27730
  current = connection;
27460
27731
  options.log(`Connected to Zopu as “${options.name}”.`);
27732
+ options.state?.(true);
27461
27733
  const closed = yield* runSession(connection, commands, options.log);
27462
27734
  current = null;
27735
+ options.state?.(false);
27463
27736
  if (yield* exports_Deferred.isDone(stopped)) {
27464
27737
  return { kind: "stopped" };
27465
27738
  }
@@ -27467,7 +27740,7 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27467
27740
  }));
27468
27741
  const loop = (failures) => exports_Effect.gen(function* retry3() {
27469
27742
  const openedAt = Date.now();
27470
- const outcome = yield* attempt();
27743
+ const outcome = yield* attempt2();
27471
27744
  if (outcome.kind === "stopped") {
27472
27745
  return "stopped";
27473
27746
  }
@@ -27491,39 +27764,55 @@ var runSatellite = (options) => exports_Effect.gen(function* satellite() {
27491
27764
  yield* exports_Effect.raceFirst(exports_Effect.sleep(wait), exports_Deferred.await(stopped));
27492
27765
  return yield* loop(next);
27493
27766
  });
27494
- return yield* loop(0).pipe(exports_Effect.ensuring(exports_Effect.sync(() => commands.shutdown())));
27767
+ return yield* loop(0).pipe(exports_Effect.ensuring(exports_Effect.sync(() => {
27768
+ commands.shutdown();
27769
+ options.state?.(false);
27770
+ })));
27495
27771
  });
27496
27772
  // src/machines.ts
27497
- var usage = `Usage: getzopu machines connect [--name <name>] [--url <url>]
27773
+ var usage = `Usage: getzopu machines connect [--name <name>] [--url <url>] [--foreground]
27498
27774
  getzopu machines status
27499
27775
  getzopu machines disconnect
27500
27776
 
27501
27777
  connect Connect this computer to your Zopu account and keep it
27502
- connected. Zopu opens a page to sign in to and prints a code to
27503
- type there; the credential then stays in a file only you can
27504
- read. Ctrl-C stops it. A computer that is already connected
27505
- connects again.
27506
- --name <name> What Zopu calls this computer
27507
- --url <url> Zopu's address (default https://zopu.live,
27508
- ZOPU_URL honoured)
27509
- status Whether this computer is connected, and to which Zopu.
27510
- disconnect Disconnect this computer from Zopu and forget the credential.
27778
+ connected. Zopu opens a page to sign in to and prints a code to
27779
+ type there; the credential then stays in a file only you can
27780
+ read. The connection then runs as a service of your account —
27781
+ it starts when you sign in and reconnects on its own — so this
27782
+ window can close. A computer that is already connected connects
27783
+ again (and takes a newer version of the program).
27784
+ --name <name> What Zopu calls this computer
27785
+ --url <url> Zopu's address (default https://zopu.live,
27786
+ ZOPU_URL honoured)
27787
+ --foreground Run the connection in this terminal instead
27788
+ (Ctrl-C stops it)
27789
+ status Whether this computer is connected, how the service is, and
27790
+ the last lines of its log.
27791
+ disconnect Stop the service, disconnect this computer from Zopu, and
27792
+ forget the credential.
27511
27793
  `;
27512
27794
  var parseFlags = (args2) => {
27513
27795
  const flags = {};
27514
27796
  for (let index2 = 0;index2 < args2.length; index2 += 1) {
27515
27797
  const arg = args2[index2] ?? "";
27516
- const takes = arg === "--name" || arg === "--url";
27517
- if (takes) {
27798
+ if (arg === "--foreground") {
27799
+ flags.foreground = true;
27800
+ continue;
27801
+ }
27802
+ if (arg === "--service") {
27803
+ flags.service = true;
27804
+ continue;
27805
+ }
27806
+ if (arg === "--name" || arg === "--url") {
27518
27807
  const value4 = args2[index2 + 1];
27519
27808
  if (!value4) {
27520
27809
  throw new Error(`${arg} requires a value.`);
27521
27810
  }
27522
27811
  flags[arg.slice(2)] = value4;
27523
27812
  index2 += 1;
27524
- } else {
27525
- throw new Error(`Unknown option: ${arg}`);
27813
+ continue;
27526
27814
  }
27815
+ throw new Error(`Unknown option: ${arg}`);
27527
27816
  }
27528
27817
  return flags;
27529
27818
  };
@@ -27593,7 +27882,7 @@ Waiting for it to be approved…
27593
27882
  serverUrl: paired.serverUrl,
27594
27883
  storedAt: Date.now()
27595
27884
  }));
27596
- console.log(`Connected. The credential is kept in ${file}, readable by you alone.
27885
+ console.log(`Paired. The credential is kept in ${file}, readable by you alone.
27597
27886
  `);
27598
27887
  } catch (error) {
27599
27888
  throw new Error(error instanceof PairingRefused ? refusal(error.reason, url) : "Zopu could not connect this computer. Try again in a moment.", { cause: error });
@@ -27601,53 +27890,209 @@ Waiting for it to be approved…
27601
27890
  process.off("SIGINT", stop);
27602
27891
  }
27603
27892
  };
27604
- var connect2 = async (flags) => {
27605
- const url = serverUrl(flags.url);
27606
- const stored = await exports_Effect.runPromise(loadCredential());
27607
- if (stored && flags.url && new URL(stored.serverUrl).origin !== url) {
27608
- throw new Error(`This computer is already connected to ${new URL(stored.serverUrl).origin}. Run getzopu machines disconnect first.`);
27893
+ var HOME = machineHome();
27894
+ var STATE_FILE = path4.join(HOME, "state.json");
27895
+ var PLAN_FILE = path4.join(HOME, "service.json");
27896
+ var writeState = async (link2) => {
27897
+ await mkdir4(HOME, { recursive: true });
27898
+ const state = { at: Date.now(), link: link2 };
27899
+ await writeFile4(STATE_FILE, JSON.stringify(state));
27900
+ };
27901
+ var readState = async () => {
27902
+ try {
27903
+ return JSON.parse(await readFile3(STATE_FILE, "utf-8"));
27904
+ } catch {
27905
+ return null;
27609
27906
  }
27610
- const name = flags.name ?? `${hostname2()} (${platform2()})`;
27611
- if (!stored) {
27612
- await pairIfNeeded(url, name);
27907
+ };
27908
+ var readPlan = async () => {
27909
+ try {
27910
+ return JSON.parse(await readFile3(PLAN_FILE, "utf-8"));
27911
+ } catch {
27912
+ return null;
27913
+ }
27914
+ };
27915
+ var logTail = async (file, lines = 6) => {
27916
+ try {
27917
+ const text = await readFile3(file, "utf-8");
27918
+ return text.split(`
27919
+ `).filter((line2) => line2.trim() !== "").slice(-lines);
27920
+ } catch {
27921
+ return [];
27613
27922
  }
27923
+ };
27924
+ var run2 = async () => {
27614
27925
  const credential2 = await exports_Effect.runPromise(loadCredential());
27615
27926
  if (!credential2) {
27616
- throw new Error("Zopu could not connect this computer. Try again in a moment.");
27927
+ return "stopped";
27617
27928
  }
27618
- console.log("This computer is connected to Zopu. Ctrl-C stops it.");
27929
+ console.log("This computer is connected to Zopu.");
27619
27930
  const controller = new AbortController;
27620
27931
  const stop = () => controller.abort();
27621
27932
  process.once("SIGINT", stop);
27622
27933
  process.once("SIGTERM", stop);
27623
- let stopped = false;
27624
27934
  try {
27625
27935
  const end2 = await exports_Effect.runPromise(runSatellite({
27626
27936
  credential: credential2.credential,
27627
27937
  journalDir: journalDir(),
27628
27938
  log: (line2) => console.log(line2),
27629
- name: credential2.name || name,
27939
+ name: credential2.name || `${hostname2()} (${platform2()})`,
27630
27940
  serverUrl: credential2.serverUrl,
27631
- signal: controller.signal
27941
+ signal: controller.signal,
27942
+ state: (connected) => {
27943
+ writeState(connected ? "connected" : "disconnected").catch(() => null);
27944
+ }
27632
27945
  }));
27633
- stopped = end2 === "stopped";
27634
27946
  if (end2 === "revoked") {
27635
27947
  await exports_Effect.runPromise(forgetCredential());
27636
- process.exitCode = 1;
27948
+ return "revoked";
27637
27949
  }
27638
27950
  } finally {
27639
27951
  process.off("SIGINT", stop);
27640
27952
  process.off("SIGTERM", stop);
27953
+ await writeState("disconnected").catch(() => null);
27954
+ }
27955
+ return "stopped";
27956
+ };
27957
+ var bundlePath = async () => {
27958
+ const file = import.meta.filename ?? "";
27959
+ if (!file.endsWith("/dist/getzopu.mjs")) {
27960
+ throw new Error("The background service needs the published program (npx getzopu …). Run with --foreground from a source checkout.");
27961
+ }
27962
+ await stat3(file);
27963
+ return file;
27964
+ };
27965
+ var planService = async () => {
27966
+ const bundle = await bundlePath();
27967
+ const copy3 = path4.join(HOME, "getzopu.mjs");
27968
+ await mkdir4(HOME, { mode: 448, recursive: true });
27969
+ await copyFile(bundle, copy3);
27970
+ const env = {};
27971
+ for (const [key, value4] of Object.entries(process.env)) {
27972
+ if (key.startsWith("ZOPU_MACHINE_") && value4 !== undefined) {
27973
+ env[key] = value4;
27974
+ }
27975
+ }
27976
+ return {
27977
+ env,
27978
+ home: HOME,
27979
+ label: serviceLabel(HOME),
27980
+ logFile: path4.join(HOME, "satellite.log"),
27981
+ path: servicePath(process.execPath, process.env.PATH ?? ""),
27982
+ program: [process.execPath, copy3, "machines", "connect", "--service"]
27983
+ };
27984
+ };
27985
+ var describe = (service4) => {
27986
+ if (service4.running) {
27987
+ return `The service is running (process ${String(service4.pid)}).`;
27988
+ }
27989
+ if (service4.installed) {
27990
+ return "The service is installed, not running.";
27991
+ }
27992
+ return "The service is not installed.";
27993
+ };
27994
+ var LINGER = 'This Linux account\'s services stop when it logs out; `loginctl enable-linger "$(id -un)"` keeps them running.';
27995
+ var awaitLink = async (since, ms) => {
27996
+ const state = await readState();
27997
+ if (state?.link === "connected" && state.at >= since) {
27998
+ return true;
27999
+ }
28000
+ if (Date.now() >= since + ms) {
28001
+ return false;
28002
+ }
28003
+ await pause(500);
28004
+ return awaitLink(since, ms);
28005
+ };
28006
+ var connect2 = async (flags) => {
28007
+ const url = serverUrl(flags.url);
28008
+ const stored = await exports_Effect.runPromise(loadCredential());
28009
+ if (stored && flags.url && new URL(stored.serverUrl).origin !== url) {
28010
+ throw new Error(`This computer is already connected to ${new URL(stored.serverUrl).origin}. Run getzopu machines disconnect first.`);
28011
+ }
28012
+ const name = flags.name ?? `${hostname2()} (${platform2()})`;
28013
+ if (flags.service) {
28014
+ if (!stored) {
28015
+ console.log("This computer has no credential to connect with; nothing to run.");
28016
+ return;
28017
+ }
28018
+ const end2 = await run2();
28019
+ console.log(end2 === "revoked" ? "This computer is disconnected from Zopu; the service will not start it again." : "Stopped.");
28020
+ return;
28021
+ }
28022
+ if (!stored) {
28023
+ await pairIfNeeded(url, name);
28024
+ }
28025
+ const credential2 = await exports_Effect.runPromise(loadCredential());
28026
+ if (!credential2) {
28027
+ throw new Error("Zopu could not connect this computer. Try again in a moment.");
27641
28028
  }
27642
- if (stopped) {
28029
+ if (flags.foreground) {
28030
+ console.log("This computer is connected to Zopu. Ctrl-C stops it.");
28031
+ const end2 = await run2();
28032
+ if (end2 === "revoked") {
28033
+ process.exitCode = 1;
28034
+ return;
28035
+ }
27643
28036
  console.log("Stopped. This computer is still connected; run getzopu machines connect to connect it again.");
28037
+ return;
27644
28038
  }
28039
+ const since = Date.now();
28040
+ const plan = await planService();
28041
+ const service4 = await exports_Effect.runPromise(installService(plan));
28042
+ await writeFile4(PLAN_FILE, JSON.stringify(plan));
28043
+ const linked = await awaitLink(since, 30000);
28044
+ if (!linked) {
28045
+ const tail = await logTail(plan.logFile);
28046
+ console.log(`Zopu could not confirm the connection in time. ${describe(service4)}
28047
+
28048
+ The last lines of its log (${plan.logFile}):
28049
+ ${tail.map((line2) => ` ${line2}`).join(`
28050
+ `)}`);
28051
+ return;
28052
+ }
28053
+ 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.");
28054
+ console.log(`
28055
+ ${describe(service4)}${service4.linger === "no" ? ` ${LINGER}` : ""}`);
28056
+ console.log(`
28057
+ getzopu machines status how it is, and the last lines of its log`);
28058
+ console.log(" getzopu machines disconnect stop it and disconnect this computer for good");
28059
+ console.log(`
28060
+ The log is ${plan.logFile}; the credential is kept in ${HOME}, readable by you alone.`);
27645
28061
  };
27646
28062
  var status = async () => {
27647
28063
  const stored = await exports_Effect.runPromise(loadCredential());
27648
- console.log(JSON.stringify(stored ? { connected: true, machineId: stored.machineId, name: stored.name, url: stored.serverUrl } : { connected: false }, null, 2));
28064
+ const plan = await readPlan();
28065
+ const service4 = plan ? await exports_Effect.runPromise(serviceStatus(plan)) : null;
28066
+ const state = await readState();
28067
+ console.log(JSON.stringify({
28068
+ link: state?.link ?? "unknown",
28069
+ machineId: stored?.machineId ?? null,
28070
+ name: stored?.name ?? null,
28071
+ paired: stored !== null,
28072
+ service: service4 ? {
28073
+ installed: service4.installed,
28074
+ linger: service4.linger,
28075
+ pid: service4.pid,
28076
+ running: service4.running
28077
+ } : null,
28078
+ url: stored?.serverUrl ?? null
28079
+ }, null, 2));
28080
+ if (plan) {
28081
+ const tail = await logTail(plan.logFile, 4);
28082
+ if (tail.length > 0) {
28083
+ console.log(`
28084
+ The last lines of its log (${plan.logFile}):`);
28085
+ for (const line2 of tail) {
28086
+ console.log(` ${line2}`);
28087
+ }
28088
+ }
28089
+ }
27649
28090
  };
27650
28091
  var disconnect = async () => {
28092
+ const plan = await readPlan();
28093
+ if (plan) {
28094
+ await exports_Effect.runPromise(exports_Effect.ignore(uninstallService(plan)));
28095
+ }
27651
28096
  const stored = await exports_Effect.runPromise(loadCredential());
27652
28097
  if (!stored) {
27653
28098
  console.log("This computer is not connected to Zopu.");
@@ -27664,7 +28109,7 @@ var disconnect = async () => {
27664
28109
  reached = false;
27665
28110
  }
27666
28111
  await exports_Effect.runPromise(forgetCredential());
27667
- 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.");
28112
+ 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.");
27668
28113
  };
27669
28114
  var runMachines = async (args2) => {
27670
28115
  const [command, ...rest] = args2;
@@ -27720,14 +28165,14 @@ Local development against http://127.0.0.1:3000 also accepts the token
27720
28165
  seeded by bun run dev:db. --json emits JSON; streams emit JSON lines.
27721
28166
  Errors exit nonzero. No token is printed.
27722
28167
  `;
27723
- var configFile = path4.join(process.env.XDG_CONFIG_HOME ?? path4.join(homedir6(), ".config"), "zopu", "config.json");
28168
+ var configFile = path6.join(process.env.XDG_CONFIG_HOME ?? path6.join(homedir7(), ".config"), "zopu", "config.json");
27724
28169
  var readConfig = async () => {
27725
28170
  try {
27726
28171
  const info = await lstat2(configFile);
27727
28172
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 63) !== 0) {
27728
28173
  throw new Error("Zopu auth config must be a private regular file (chmod 600).");
27729
28174
  }
27730
- const value4 = JSON.parse(await readFile3(configFile, "utf-8"));
28175
+ const value4 = JSON.parse(await readFile4(configFile, "utf-8"));
27731
28176
  if (typeof value4 !== "object" || value4 === null) {
27732
28177
  throw new Error("Invalid Zopu auth configuration.");
27733
28178
  }
@@ -27745,8 +28190,8 @@ var readConfig = async () => {
27745
28190
  var LOOPBACK_HOSTS2 = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
27746
28191
  var readDevToken = async () => {
27747
28192
  const candidates = [
27748
- path4.join(process.cwd(), ".dev", "zopu-cli-token"),
27749
- path4.join(path4.resolve(process.cwd(), ".."), ".dev", "zopu-cli-token")
28193
+ path6.join(process.cwd(), ".dev", "zopu-cli-token"),
28194
+ path6.join(path6.resolve(process.cwd(), ".."), ".dev", "zopu-cli-token")
27750
28195
  ];
27751
28196
  for (const candidate of candidates) {
27752
28197
  try {
@@ -27754,7 +28199,7 @@ var readDevToken = async () => {
27754
28199
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 63) !== 0) {
27755
28200
  continue;
27756
28201
  }
27757
- const contents = await readFile3(candidate, "utf-8");
28202
+ const contents = await readFile4(candidate, "utf-8");
27758
28203
  const value4 = contents.trim();
27759
28204
  if (/^zopu_key_[A-Za-z0-9_-]{43}$/u.test(value4)) {
27760
28205
  return value4;
@@ -27857,9 +28302,9 @@ var main = async () => {
27857
28302
  throw new Error("Invalid Zopu API token.");
27858
28303
  }
27859
28304
  await createZopuClient({ baseUrl: url, token: received }).projects.list();
27860
- await mkdir4(path4.dirname(configFile), { mode: 448, recursive: true });
28305
+ await mkdir5(path6.dirname(configFile), { mode: 448, recursive: true });
27861
28306
  const temporary = `${configFile}.${process.pid}.tmp`;
27862
- await writeFile3(temporary, `${JSON.stringify({ token: received, url })}
28307
+ await writeFile5(temporary, `${JSON.stringify({ token: received, url })}
27863
28308
  `, {
27864
28309
  flag: "wx",
27865
28310
  mode: 384
@@ -27912,7 +28357,7 @@ var main = async () => {
27912
28357
  throw new Error("Not signed in. Create a token in Zopu Profile, then use auth login --token-stdin.");
27913
28358
  }
27914
28359
  const client = createZopuClient({ baseUrl: url, token });
27915
- const input = values2.input ? objectInput(values2.input === "-" ? await stdin() : await readFile3(values2.input, "utf-8")) : {};
28360
+ const input = values2.input ? objectInput(values2.input === "-" ? await stdin() : await readFile4(values2.input, "utf-8")) : {};
27916
28361
  if (["delete", "archive"].includes(command ?? "") && !values2.yes) {
27917
28362
  throw new Error("This action requires --yes.");
27918
28363
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "getzopu",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Zopu CLI: projects, threads, and connecting your own computer to Zopu.",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {