@reasontrail/cli 0.1.0 → 0.1.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.
@@ -1 +1 @@
1
- {"sourceRevision":"a740bfd0d01cdbeafaca5cc7bffc83ee5bcca0cb"}
1
+ {"sourceRevision":"ff10c2011417a7a8c6ecd193e70e1d2b9bff1d33"}
package/src/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { createHash } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmod, copyFile, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { deviceLogin } from "./device-login.mjs";
@@ -24,6 +24,7 @@ const PACKAGE_ROOT = resolve(new URL("..", import.meta.url).pathname);
24
24
  const PACKAGE_META = JSON.parse(await readFile(join(PACKAGE_ROOT, "package.json"), "utf8"));
25
25
  const VERSION = PACKAGE_META.version;
26
26
  const PROFILE_NAMES = new Set(["development", "production"]);
27
+ const SERVICE_NAME_PREFIX = "reasontrail-sync";
27
28
 
28
29
  function profileDir(profile) {
29
30
  return join(CONFIG_DIR, "profiles", profile);
@@ -367,6 +368,27 @@ function output(value) {
367
368
  stdout.write(`${JSON.stringify(value, null, 2)}\n`);
368
369
  }
369
370
 
371
+ function serviceSafeName(value) {
372
+ return String(value || "")
373
+ .toLowerCase()
374
+ .replace(/[^a-z0-9_.-]+/g, "-")
375
+ .replace(/^-+|-+$/g, "")
376
+ .slice(0, 80) || "default";
377
+ }
378
+
379
+ function plistEscape(value) {
380
+ return String(value)
381
+ .replaceAll("&", "&")
382
+ .replaceAll("<", "&lt;")
383
+ .replaceAll(">", "&gt;")
384
+ .replaceAll('"', "&quot;")
385
+ .replaceAll("'", "&apos;");
386
+ }
387
+
388
+ function systemdQuote(value) {
389
+ return `"${String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
390
+ }
391
+
370
392
  function options(args) {
371
393
  const values = { _: [] };
372
394
  for (let i = 0; i < args.length; i += 1) {
@@ -507,10 +529,15 @@ async function runCommand(argv) {
507
529
  const { binding } = await bindingFor(target);
508
530
  const request = opts.task ? undefined : opts._.join(" ").trim();
509
531
  if (!opts.task && !request) throw new CliError('Usage: reasontrail run "<task>" | reasontrail run --task <task-id>', 2);
532
+ const requestId = opts["request-id"] ? String(opts["request-id"]) : randomUUID();
510
533
  return output(await runtimeTool(target, "runtime_start", {
511
534
  ...(opts.task ? { taskId: String(opts.task) } : { request }),
512
535
  ...(opts.title ? { title: String(opts.title) } : {}),
513
536
  ...(opts.workspace ? { workspaceId: String(opts.workspace) } : {}),
537
+ ...(opts.task ? {
538
+ workerKey: String(opts.worker || "codex-cli"),
539
+ idempotencyKey: `work-cli:${String(opts.task)}:${requestId}`,
540
+ } : {}),
514
541
  ...(opts.project || binding?.projectSlug ? { projectSlug: String(opts.project || binding.projectSlug) } : {}),
515
542
  }));
516
543
  }
@@ -840,8 +867,11 @@ async function doctorCommand(argv) {
840
867
 
841
868
  async function syncCommand(argv) {
842
869
  const sub = argv[0];
843
- if (!["codex", "docs"].includes(sub)) {
844
- throw new CliError("Usage: reasontrail sync codex|docs --profile <profile> [--apply] [--watch] [--interval <seconds>] [--since <time>] [--project <slug>] [--session <id>]", 2);
870
+ if (!["codex", "docs", "managed", "service"].includes(sub)) {
871
+ throw new CliError("Usage: reasontrail sync codex|docs|managed|service --profile <profile> [--apply] [--watch] [--interval <seconds>] [--project <slug>]", 2);
872
+ }
873
+ if (sub === "service") {
874
+ return syncServiceCommand(argv.slice(1));
845
875
  }
846
876
  const target = await resolveTarget(argv.slice(1), { confirm: false });
847
877
  const opts = target.opts;
@@ -864,6 +894,22 @@ async function syncCommand(argv) {
864
894
  const { binding } = await bindingFor(target);
865
895
  return client.call("sync_docs", { ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}) });
866
896
  }
897
+ if (sub === "managed") {
898
+ if (!apply) throw new CliError("Managed sync writes conversation and documentation updates into ReasonTrail. Add `--apply` when you intentionally want background capture.", 2);
899
+ const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
900
+ dryRun: false,
901
+ since: opts.since || null,
902
+ project: opts.project || null,
903
+ session: opts.session || null,
904
+ force: Boolean(opts.force),
905
+ });
906
+ let docs = null;
907
+ if (hasTool(tools, "sync_docs")) {
908
+ const { binding } = await bindingFor(target);
909
+ docs = await client.call("sync_docs", { ...(opts.project || binding?.projectSlug ? { projectSlug: opts.project || binding.projectSlug } : {}) });
910
+ }
911
+ return { synchronized: true, codex, docs };
912
+ }
867
913
  return syncCodex(client, tools, target.paths.dir, target.cfg, {
868
914
  dryRun: !apply,
869
915
  since: opts.since || null,
@@ -879,6 +925,131 @@ async function syncCommand(argv) {
879
925
  }
880
926
  }
881
927
 
928
+ async function syncServiceCommand(argv) {
929
+ const action = argv[0];
930
+ if (!["install", "status", "start", "stop", "uninstall"].includes(action)) {
931
+ throw new CliError("Usage: reasontrail sync service install|status|start|stop|uninstall --profile <profile> [--project <slug>] [--interval <seconds>] [--system]", 2);
932
+ }
933
+ const target = await resolveTarget(argv.slice(1), { confirm: false });
934
+ const opts = target.opts;
935
+ const { root, binding } = await bindingFor(target);
936
+ const project = opts.project || binding?.projectSlug;
937
+ const intervalSeconds = Math.max(10, Math.min(3600, Number(opts.interval || 60)));
938
+ if (!Number.isFinite(intervalSeconds)) throw new CliError("Sync interval must be a number of seconds.", 2);
939
+ const serviceName = `${SERVICE_NAME_PREFIX}-${serviceSafeName(target.profile)}${project ? `-${serviceSafeName(project)}` : ""}`;
940
+ const script = resolve(process.argv[1]);
941
+ const args = [
942
+ script,
943
+ "sync",
944
+ "managed",
945
+ "--profile",
946
+ target.profile,
947
+ "--apply",
948
+ "--watch",
949
+ "--interval",
950
+ String(intervalSeconds),
951
+ ...(project ? ["--project", project] : []),
952
+ ...(target.profile === "production" ? ["--confirm-production"] : []),
953
+ ];
954
+
955
+ if (action === "install") {
956
+ if (!project) throw new CliError("Install requires a project. Bind this repository first with `reasontrail . --project <slug>` or pass `--project <slug>`.", 2);
957
+ if (process.platform === "linux") {
958
+ const system = opts.system === true;
959
+ const servicePath = system
960
+ ? `/etc/systemd/system/${serviceName}.service`
961
+ : join(homedir(), ".config", "systemd", "user", `${serviceName}.service`);
962
+ const unit = [
963
+ "[Unit]",
964
+ `Description=ReasonTrail managed capture (${target.profile}/${project})`,
965
+ "After=network-online.target",
966
+ "Wants=network-online.target",
967
+ "",
968
+ "[Service]",
969
+ "Type=simple",
970
+ `Environment=${systemdQuote(`HOME=${homedir()}`)}`,
971
+ `Environment=${systemdQuote(`XDG_CONFIG_HOME=${process.env.XDG_CONFIG_HOME || join(homedir(), ".config")}`)}`,
972
+ `Environment=${systemdQuote(`CODEX_HOME=${process.env.CODEX_HOME || join(homedir(), ".codex")}`)}`,
973
+ `WorkingDirectory=${root}`,
974
+ `ExecStart=${systemdQuote(process.execPath)} ${args.map(systemdQuote).join(" ")}`,
975
+ "Restart=always",
976
+ "RestartSec=15",
977
+ "",
978
+ "[Install]",
979
+ "WantedBy=default.target",
980
+ "",
981
+ ].join("\n");
982
+ await mkdir(dirname(servicePath), { recursive: true, mode: 0o755 });
983
+ await writeFile(servicePath, unit, { mode: 0o644 });
984
+ return output({
985
+ installed: true,
986
+ platform: "linux",
987
+ manager: system ? "systemd-system" : "systemd-user",
988
+ service: serviceName,
989
+ path: servicePath,
990
+ projectSlug: project,
991
+ next: system
992
+ ? [`systemctl daemon-reload`, `systemctl enable --now ${serviceName}.service`, `systemctl status ${serviceName}.service`]
993
+ : [`systemctl --user daemon-reload`, `systemctl --user enable --now ${serviceName}.service`, `systemctl --user status ${serviceName}.service`],
994
+ });
995
+ }
996
+ if (process.platform === "darwin") {
997
+ const label = `ai.reasontrail.${serviceName}`;
998
+ const plistPath = join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
999
+ const programArguments = [process.execPath, ...args].map((arg) => ` <string>${plistEscape(arg)}</string>`);
1000
+ const plist = [
1001
+ `<?xml version="1.0" encoding="UTF-8"?>`,
1002
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
1003
+ `<plist version="1.0">`,
1004
+ `<dict>`,
1005
+ ` <key>Label</key><string>${plistEscape(label)}</string>`,
1006
+ ` <key>WorkingDirectory</key><string>${plistEscape(root)}</string>`,
1007
+ ` <key>ProgramArguments</key>`,
1008
+ ` <array>`,
1009
+ ...programArguments,
1010
+ ` </array>`,
1011
+ ` <key>KeepAlive</key><true/>`,
1012
+ ` <key>RunAtLoad</key><true/>`,
1013
+ ` <key>StandardOutPath</key><string>${plistEscape(join(CONFIG_DIR, `${serviceName}.out.log`))}</string>`,
1014
+ ` <key>StandardErrorPath</key><string>${plistEscape(join(CONFIG_DIR, `${serviceName}.err.log`))}</string>`,
1015
+ `</dict>`,
1016
+ `</plist>`,
1017
+ ``,
1018
+ ].join("\n");
1019
+ await mkdir(dirname(plistPath), { recursive: true, mode: 0o755 });
1020
+ await writeFile(plistPath, plist, { mode: 0o644 });
1021
+ return output({ installed: true, platform: "darwin", manager: "launchd", service: label, path: plistPath, projectSlug: project, next: [`launchctl bootstrap gui/$(id -u) ${plistPath}`, `launchctl print gui/$(id -u)/${label}`] });
1022
+ }
1023
+ throw new CliError(`Managed sync service install is not implemented for ${process.platform}. Use \`reasontrail sync managed --apply --watch\` under your OS service manager.`, 2);
1024
+ }
1025
+
1026
+ if (process.platform === "linux") {
1027
+ const system = opts.system === true;
1028
+ const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
1029
+ const verb = action === "uninstall" ? "disable" : action;
1030
+ if (action === "uninstall") {
1031
+ const result = spawnSync(ctl[0], [...ctl.slice(1), "disable", "--now", `${serviceName}.service`], { encoding: "utf8" });
1032
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `Could not disable ${serviceName}.service`, 3);
1033
+ return output({ removed: false, disabled: true, service: serviceName, note: "The unit file was left in place; remove it manually if you no longer need it." });
1034
+ }
1035
+ const result = spawnSync(ctl[0], [...ctl.slice(1), verb, `${serviceName}.service`], { encoding: "utf8" });
1036
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `systemctl ${verb} failed`, 3);
1037
+ return output({ ok: true, manager: system ? "systemd-system" : "systemd-user", action, service: serviceName, output: result.stdout.trim() });
1038
+ }
1039
+ if (process.platform === "darwin") {
1040
+ const label = `ai.reasontrail.${serviceName}`;
1041
+ const gui = `gui/${process.getuid?.() ?? "$(id -u)"}`;
1042
+ const command = action === "status" ? ["print", `${gui}/${label}`]
1043
+ : action === "start" ? ["kickstart", "-k", `${gui}/${label}`]
1044
+ : action === "stop" ? ["bootout", `${gui}/${label}`]
1045
+ : ["bootout", `${gui}/${label}`];
1046
+ const result = spawnSync("launchctl", command, { encoding: "utf8" });
1047
+ if (result.status !== 0) throw new CliError(result.stderr.trim() || `launchctl ${action} failed`, 3);
1048
+ return output({ ok: true, manager: "launchd", action, service: label, output: result.stdout.trim() });
1049
+ }
1050
+ throw new CliError(`Managed sync service ${action} is not implemented for ${process.platform}.`, 2);
1051
+ }
1052
+
882
1053
  async function inspectClaudeMcp(profile) {
883
1054
  // Assistant-wide MCP diagnostics can probe registrations for other profiles.
884
1055
  // Keep doctor restricted to its own authenticated connection above.
@@ -1176,9 +1347,10 @@ async function runtimeConfig(profile) {
1176
1347
  function runtimeUsage() {
1177
1348
  return (
1178
1349
  `Usage: reasontrail runtime <command>\n\n` +
1179
- ` enroll --url <origin> --token <rtrt_…> [--workspace <id>=<path>]…\n` +
1350
+ ` enroll --url <origin> --token <rtrt_…> --execution-root <path> [--dependency-network disabled|public] [--workspace <id>=<path>]…\n` +
1180
1351
  ` Store this machine's enrollment\n` +
1181
- ` start [--once] Connect to ReasonTrail and take work\n` +
1352
+ ` start [--once] [--dependency-network disabled|public]\n` +
1353
+ ` Connect to ReasonTrail and take work\n` +
1182
1354
  ` status Show the stored enrollment\n` +
1183
1355
  ` logout Forget the stored enrollment\n`
1184
1356
  );
@@ -1198,7 +1370,12 @@ async function runtimeCommand(argv) {
1198
1370
  };
1199
1371
  const url = value("--url");
1200
1372
  const token = value("--token");
1201
- if (!url || !token) throw new CliError("Both --url and --token are required.\n\n" + runtimeUsage(), 2);
1373
+ const executionRoot = value("--execution-root");
1374
+ const dependencyNetwork = value("--dependency-network") || "disabled";
1375
+ if (!url || !token || !executionRoot) throw new CliError("--url, --token and --execution-root are required.\n\n" + runtimeUsage(), 2);
1376
+ if (!["disabled", "public"].includes(dependencyNetwork)) {
1377
+ throw new CliError("--dependency-network must be 'disabled' or 'public'.", 2);
1378
+ }
1202
1379
  if (!token.startsWith("rtrt_")) {
1203
1380
  throw new CliError("That does not look like a runtime credential (expected an rtrt_ prefix).", 2);
1204
1381
  }
@@ -1220,10 +1397,18 @@ async function runtimeCommand(argv) {
1220
1397
  // 0600, in a 0700 directory. The credential is the whole point of the file.
1221
1398
  if (target.profile === "production" && origin !== "https://app.reasontrail.ai") throw new CliError("Production runtime enrollment must use https://app.reasontrail.ai.", 2);
1222
1399
  if (target.profile === "development" && !["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname)) throw new CliError("Development runtime enrollment accepts only a loopback origin.", 2);
1223
- await saveJson(runtimeFile, { origin, token, workspaces }, 0o600);
1400
+ await saveJson(runtimeFile, {
1401
+ origin,
1402
+ token,
1403
+ workspaces,
1404
+ executionRoot: resolve(executionRoot),
1405
+ dependencyNetwork,
1406
+ }, 0o600);
1224
1407
  stdout.write(
1225
1408
  `Enrolled against ${origin}.\n` +
1226
1409
  `${workspaces.length} workspace${workspaces.length === 1 ? "" : "s"} configured.\n` +
1410
+ `Disposable execution root: ${resolve(executionRoot)}\n` +
1411
+ `Dependency network: ${dependencyNetwork}\n` +
1227
1412
  `Stored in ${runtimeFile} (owner-only).\n\n` +
1228
1413
  `Start it with: reasontrail runtime start --profile ${target.profile}\n`
1229
1414
  );
@@ -1240,6 +1425,8 @@ async function runtimeCommand(argv) {
1240
1425
  ` Instance ${cfg.origin}\n` +
1241
1426
  ` Credential ${prefix}… (stored, not shown)\n` +
1242
1427
  ` Workspaces ${cfg.workspaces?.length ? cfg.workspaces.join(", ") : "none — map them in ReasonTrail after connecting"}\n` +
1428
+ ` Exec root ${cfg.executionRoot || "not configured — provider execution disabled"}\n` +
1429
+ ` Dep network ${cfg.dependencyNetwork || "disabled"}\n` +
1243
1430
  ` Bundle ${RUNTIME_BUNDLE}\n\n` +
1244
1431
  `Live status — protocol, workers, readiness — is shown by ReasonTrail itself,\n` +
1245
1432
  `which is the authority on all three. This command reports local setup only.\n`
@@ -1268,6 +1455,13 @@ async function runtimeCommand(argv) {
1268
1455
 
1269
1456
  const args = [RUNTIME_BUNDLE, "run"];
1270
1457
  for (const workspace of cfg.workspaces ?? []) args.push("--workspace", workspace);
1458
+ if (cfg.executionRoot) args.push("--execution-root", cfg.executionRoot);
1459
+ const networkFlagIndex = argv.indexOf("--dependency-network");
1460
+ const dependencyNetwork = networkFlagIndex >= 0 ? argv[networkFlagIndex + 1] : (cfg.dependencyNetwork || "disabled");
1461
+ if (!["disabled", "public"].includes(dependencyNetwork)) {
1462
+ throw new CliError("--dependency-network must be 'disabled' or 'public'.", 2);
1463
+ }
1464
+ args.push("--dependency-network", dependencyNetwork);
1271
1465
  if (argv.includes("--once")) args.push("--once");
1272
1466
 
1273
1467
  // The credential is passed through the environment of the child and never
@@ -1302,8 +1496,10 @@ function helpCommand() {
1302
1496
  ` install --platform <name> Install the assistant skill\n` +
1303
1497
  ` uninstall --platform <name> Remove the assistant skill\n` +
1304
1498
  ` setup --profile <profile> Configure detected assistants (hooks require --enable-hooks in development)\n` +
1305
- ` sync codex --profile <profile> Preview local Codex sessions; add --apply and optionally --watch\n` +
1306
- ` sync docs --profile <profile> Synchronize repository Markdown docs; requires --apply; optionally --watch\n` +
1499
+ ` sync codex --profile <profile> Preview local Codex sessions; add --apply and optionally --watch\n` +
1500
+ ` sync docs --profile <profile> Synchronize repository Markdown docs; requires --apply; optionally --watch\n` +
1501
+ ` sync managed --profile <profile> Sync eligible Codex sessions and Markdown docs together\n` +
1502
+ ` sync service install|status Manage OS background capture for one profile/project\n` +
1307
1503
  ` hook claude Receive a Claude Code lifecycle hook event\n` +
1308
1504
  ` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +
1309
1505
  ` runtime enroll|start|status|logout ReasonTrail Runtime on this machine\n` +