@jive-ai/cli 0.0.45 → 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -28,9 +28,16 @@ import httpProxy from "http-proxy";
28
28
 
29
29
  //#region src/lib/config.ts
30
30
  /**
31
+ * Get the effective home directory - uses SUDO_USER's home when running with sudo
32
+ */
33
+ function getEffectiveHomeDir() {
34
+ if (process.env.SUDO_USER) return `/home/${process.env.SUDO_USER}`;
35
+ return os.homedir();
36
+ }
37
+ /**
31
38
  * `~/.jive/credentials.json`
32
39
  */
33
- const CREDENTIALS_PATH = path.join(os.homedir(), ".jive", "credentials.json");
40
+ const CREDENTIALS_PATH = path.join(getEffectiveHomeDir(), ".jive", "credentials.json");
34
41
  /**
35
42
  * `<cwd>/.jive/config.json`
36
43
  */
@@ -1023,6 +1030,48 @@ const mutations = {
1023
1030
  }
1024
1031
  }
1025
1032
  }
1033
+ `),
1034
+ CreateIssue: graphql(`
1035
+ mutation CreateIssue($input: CreateIssueInput!) {
1036
+ createIssue(input: $input) {
1037
+ success
1038
+ issue {
1039
+ id
1040
+ number
1041
+ title
1042
+ htmlUrl
1043
+ labels {
1044
+ name
1045
+ color
1046
+ }
1047
+ }
1048
+ errors {
1049
+ message
1050
+ code
1051
+ }
1052
+ }
1053
+ }
1054
+ `),
1055
+ UpdateIssue: graphql(`
1056
+ mutation UpdateIssue($input: UpdateIssueInput!) {
1057
+ updateIssue(input: $input) {
1058
+ success
1059
+ issue {
1060
+ id
1061
+ number
1062
+ title
1063
+ htmlUrl
1064
+ labels {
1065
+ name
1066
+ color
1067
+ }
1068
+ }
1069
+ errors {
1070
+ message
1071
+ code
1072
+ }
1073
+ }
1074
+ }
1026
1075
  `),
1027
1076
  RegisterRunner: graphql(`
1028
1077
  mutation RegisterRunner($input: RegisterRunnerInput!) {
@@ -1563,6 +1612,46 @@ var ApiClient = class {
1563
1612
  }
1564
1613
  };
1565
1614
  }
1615
+ async createIssue(projectId, data) {
1616
+ const result = await (await getGraphQLClient()).request(mutations.CreateIssue, { input: {
1617
+ projectId: String(projectId),
1618
+ title: data.title,
1619
+ body: data.body,
1620
+ labels: data.labels
1621
+ } });
1622
+ if (result.createIssue.errors?.length) throw this.formatError({ message: result.createIssue.errors[0].message });
1623
+ return {
1624
+ success: result.createIssue.success,
1625
+ issue: {
1626
+ id: result.createIssue.issue.id,
1627
+ number: result.createIssue.issue.number,
1628
+ title: result.createIssue.issue.title,
1629
+ htmlUrl: result.createIssue.issue.htmlUrl,
1630
+ labels: result.createIssue.issue.labels
1631
+ }
1632
+ };
1633
+ }
1634
+ async updateIssue(projectId, data) {
1635
+ const result = await (await getGraphQLClient()).request(mutations.UpdateIssue, { input: {
1636
+ projectId: String(projectId),
1637
+ number: data.number,
1638
+ title: data.title,
1639
+ body: data.body,
1640
+ state: data.state,
1641
+ labels: data.labels
1642
+ } });
1643
+ if (result.updateIssue.errors?.length) throw this.formatError({ message: result.updateIssue.errors[0].message });
1644
+ return {
1645
+ success: result.updateIssue.success,
1646
+ issue: {
1647
+ id: result.updateIssue.issue.id,
1648
+ number: result.updateIssue.issue.number,
1649
+ title: result.updateIssue.issue.title,
1650
+ htmlUrl: result.updateIssue.issue.htmlUrl,
1651
+ labels: result.updateIssue.issue.labels
1652
+ }
1653
+ };
1654
+ }
1566
1655
  async getTaskSteps(id) {
1567
1656
  const data = await (await getGraphQLClient()).request(queries.GetPlan, { id: String(id) });
1568
1657
  if (!data.plan?.steps) return [];
@@ -1961,7 +2050,7 @@ async function createGraphQLClient() {
1961
2050
 
1962
2051
  //#endregion
1963
2052
  //#region package.json
1964
- var version = "0.0.45";
2053
+ var version = "0.0.46";
1965
2054
 
1966
2055
  //#endregion
1967
2056
  //#region src/runner/index.ts
@@ -2184,7 +2273,6 @@ var TaskRunner = class {
2184
2273
  const url = new URL(WS_URL);
2185
2274
  url.searchParams.set("apiKey", jiveApiKey);
2186
2275
  url.searchParams.set("runnerId", this.config.id.toString());
2187
- console.log(chalk.dim(`Connecting to ${url.toString()}...`));
2188
2276
  this.ws = new WebSocket(url.toString());
2189
2277
  this.ws.on("open", () => this.handleOpen());
2190
2278
  this.ws.on("message", (data) => this.handleMessage(data));
@@ -2714,6 +2802,104 @@ function createTasksSdkServer(task) {
2714
2802
  isError: true
2715
2803
  };
2716
2804
  }
2805
+ }),
2806
+ tool("create_issue", "Create an issue on GitHub or GitLab for the current project. Use this to track bugs, feature requests, or other work items.", {
2807
+ title: z.string().describe("Issue title - a concise summary of the issue"),
2808
+ body: z.string().describe("Issue body/description - detailed explanation of the issue"),
2809
+ labels: z.array(z.string()).optional().describe("Optional labels to apply to the issue")
2810
+ }, async (args) => {
2811
+ if (!context) return {
2812
+ content: [{
2813
+ type: "text",
2814
+ text: "Error: Task context not initialized"
2815
+ }],
2816
+ isError: true
2817
+ };
2818
+ try {
2819
+ const apiClient$1 = getApiClient();
2820
+ const { project } = await apiClient$1.getTask(context.taskId);
2821
+ if (!project) return {
2822
+ content: [{
2823
+ type: "text",
2824
+ text: "Error: Project not found for this task"
2825
+ }],
2826
+ isError: true
2827
+ };
2828
+ task.debugLog(`Creating issue: ${args.title}`);
2829
+ const result = await apiClient$1.createIssue(project.id, {
2830
+ title: args.title,
2831
+ body: args.body,
2832
+ labels: args.labels
2833
+ });
2834
+ task.debugLog(`Issue created: ${JSON.stringify(result, null, 2)}`);
2835
+ return { content: [{
2836
+ type: "text",
2837
+ text: JSON.stringify({
2838
+ success: true,
2839
+ projectId: project.id,
2840
+ issue: result.issue
2841
+ }, null, 2)
2842
+ }] };
2843
+ } catch (error$1) {
2844
+ return {
2845
+ content: [{
2846
+ type: "text",
2847
+ text: `Error creating issue: ${error$1.message}`
2848
+ }],
2849
+ isError: true
2850
+ };
2851
+ }
2852
+ }),
2853
+ tool("update_issue", "Update an existing issue on GitHub or GitLab. Use this to modify issue title, body, state (open/closed), or labels.", {
2854
+ number: z.number().describe("Issue number to update"),
2855
+ title: z.string().optional().describe("New title for the issue"),
2856
+ body: z.string().optional().describe("New body/description for the issue"),
2857
+ state: z.enum(["open", "closed"]).optional().describe("Issue state - \"open\" or \"closed\""),
2858
+ labels: z.array(z.string()).optional().describe("Labels to set on the issue (replaces existing labels)")
2859
+ }, async (args) => {
2860
+ if (!context) return {
2861
+ content: [{
2862
+ type: "text",
2863
+ text: "Error: Task context not initialized"
2864
+ }],
2865
+ isError: true
2866
+ };
2867
+ try {
2868
+ const apiClient$1 = getApiClient();
2869
+ const { project } = await apiClient$1.getTask(context.taskId);
2870
+ if (!project) return {
2871
+ content: [{
2872
+ type: "text",
2873
+ text: "Error: Project not found for this task"
2874
+ }],
2875
+ isError: true
2876
+ };
2877
+ task.debugLog(`Updating issue #${args.number}`);
2878
+ const result = await apiClient$1.updateIssue(project.id, {
2879
+ number: args.number,
2880
+ title: args.title,
2881
+ body: args.body,
2882
+ state: args.state,
2883
+ labels: args.labels
2884
+ });
2885
+ task.debugLog(`Issue updated: ${JSON.stringify(result, null, 2)}`);
2886
+ return { content: [{
2887
+ type: "text",
2888
+ text: JSON.stringify({
2889
+ success: true,
2890
+ projectId: project.id,
2891
+ issue: result.issue
2892
+ }, null, 2)
2893
+ }] };
2894
+ } catch (error$1) {
2895
+ return {
2896
+ content: [{
2897
+ type: "text",
2898
+ text: `Error updating issue: ${error$1.message}`
2899
+ }],
2900
+ isError: true
2901
+ };
2902
+ }
2717
2903
  })
2718
2904
  ]
2719
2905
  });
@@ -3732,6 +3918,17 @@ Host gitlab.com
3732
3918
  this.claudeAbortController = null;
3733
3919
  this.sendStatusUpdate("idle");
3734
3920
  }
3921
+ reportUsage(message) {
3922
+ if (!("total_cost_usd" in message)) return;
3923
+ this.sendToTaskRunner({
3924
+ type: "usage",
3925
+ payload: { usage: {
3926
+ total_cost_usd: message.total_cost_usd,
3927
+ total_input_tokens: message.usage.input_tokens,
3928
+ total_output_tokens: message.usage.output_tokens
3929
+ } }
3930
+ });
3931
+ }
3735
3932
  async queryClaude(prompt, mode = "BYPASS_PERMISSIONS") {
3736
3933
  if (this.status !== "idle") {
3737
3934
  this.debugLog(`WARNING: queryClaude called while status is '${this.status}'`);
@@ -3750,7 +3947,7 @@ Host gitlab.com
3750
3947
  permissionMode: mode,
3751
3948
  task: this
3752
3949
  });
3753
- for await (const _message of result);
3950
+ for await (const message of result) if (message.type === "result") this.reportUsage(message);
3754
3951
  const finalLines = await this.readNewSessionLines();
3755
3952
  for (const line of finalLines) try {
3756
3953
  const parsed = JSON.parse(line);
@@ -4139,7 +4336,7 @@ async function installServiceCommand() {
4139
4336
  console.log(chalk.bold("\nJive Task Runner Service Installation"));
4140
4337
  console.log(chalk.dim("=========================================\n"));
4141
4338
  try {
4142
- const { getServiceManager, validateServiceInstallation, detectPlatform } = await import("./service-4H4YceKv.mjs");
4339
+ const { getServiceManager, validateServiceInstallation, detectPlatform } = await import("./service-MMjLsA9C.mjs");
4143
4340
  if (detectPlatform() === "unsupported") {
4144
4341
  console.error(chalk.red("Service installation is not supported on this platform."));
4145
4342
  console.log(chalk.dim("\nCurrently supported platforms:"));
@@ -4171,7 +4368,8 @@ async function installServiceCommand() {
4171
4368
  }
4172
4369
  if (validation.hasWarnings) console.log(chalk.yellow("\n⚠ Installation can proceed, but there are warnings."));
4173
4370
  console.log(chalk.dim(`\nPlatform: Linux (systemd)`));
4174
- console.log(chalk.dim(`Service file: ~/.config/systemd/user/jive-task-runner.service\n`));
4371
+ console.log(chalk.dim(`Service file: /etc/systemd/system/jive-task-runner.service`));
4372
+ console.log(chalk.dim(`Credentials: /etc/jive/runner.env\n`));
4175
4373
  const { confirm } = await prompts({
4176
4374
  type: "confirm",
4177
4375
  name: "confirm",
@@ -4182,8 +4380,9 @@ async function installServiceCommand() {
4182
4380
  console.log(chalk.yellow("Installation cancelled"));
4183
4381
  return;
4184
4382
  }
4185
- spinner.start("Creating service file...");
4186
4383
  const manager = getServiceManager();
4384
+ await manager.checkAndMigrateLegacyService();
4385
+ spinner.start("Creating service file...");
4187
4386
  await manager.install();
4188
4387
  spinner.succeed("Service installed successfully!");
4189
4388
  const { startNow } = await prompts({
@@ -4201,9 +4400,10 @@ async function installServiceCommand() {
4201
4400
  if (status.uptime) console.log(chalk.dim(`Uptime: ${status.uptime}`));
4202
4401
  }
4203
4402
  console.log(chalk.bold("\nNext steps:"));
4204
- console.log(chalk.dim(" • View logs: ") + chalk.cyan("jive task-runner service-logs"));
4205
- console.log(chalk.dim(" • Check status: ") + chalk.cyan("jive task-runner service-status"));
4206
- console.log(chalk.dim(" • Restart: ") + chalk.cyan("jive task-runner service-restart"));
4403
+ console.log(chalk.dim(" • View logs: ") + chalk.cyan("journalctl -u jive-task-runner -f"));
4404
+ console.log(chalk.dim(" • Check status: ") + chalk.cyan("systemctl status jive-task-runner"));
4405
+ console.log(chalk.dim(" • Restart: ") + chalk.cyan("sudo systemctl restart jive-task-runner"));
4406
+ console.log(chalk.dim(" • Uninstall: ") + chalk.cyan("jive task-runner uninstall-service"));
4207
4407
  } catch (error$1) {
4208
4408
  console.error(chalk.red(`\n✗ Installation failed: ${error$1.message}`));
4209
4409
  process.exit(1);
@@ -4214,7 +4414,7 @@ async function installServiceCommand() {
4214
4414
  */
4215
4415
  async function uninstallServiceCommand() {
4216
4416
  try {
4217
- const { getServiceManager } = await import("./service-4H4YceKv.mjs");
4417
+ const { getServiceManager } = await import("./service-MMjLsA9C.mjs");
4218
4418
  const manager = getServiceManager();
4219
4419
  if (!await manager.isInstalled()) {
4220
4420
  console.log(chalk.yellow("Service is not installed."));
@@ -4244,7 +4444,7 @@ async function uninstallServiceCommand() {
4244
4444
  */
4245
4445
  async function serviceStatusCommand() {
4246
4446
  try {
4247
- const { getServiceManager } = await import("./service-4H4YceKv.mjs");
4447
+ const { getServiceManager } = await import("./service-MMjLsA9C.mjs");
4248
4448
  const manager = getServiceManager();
4249
4449
  if (!await manager.isInstalled()) {
4250
4450
  console.log(chalk.dim("Service is not installed."));
@@ -4276,10 +4476,10 @@ async function serviceStatusCommand() {
4276
4476
  }
4277
4477
  console.log(chalk.bold("\nCommands:"));
4278
4478
  console.log(chalk.dim("─".repeat(60)));
4279
- console.log(chalk.dim(" Logs: ") + chalk.cyan("jive task-runner service-logs [-f]"));
4280
- console.log(chalk.dim(" Restart: ") + chalk.cyan("jive task-runner service-restart"));
4281
- if (status.running) console.log(chalk.dim(" Stop: ") + chalk.cyan("systemctl --user stop jive-task-runner"));
4282
- else console.log(chalk.dim(" Start: ") + chalk.cyan("systemctl --user start jive-task-runner"));
4479
+ console.log(chalk.dim(" Logs: ") + chalk.cyan("journalctl -u jive-task-runner -f"));
4480
+ console.log(chalk.dim(" Restart: ") + chalk.cyan("sudo systemctl restart jive-task-runner"));
4481
+ if (status.running) console.log(chalk.dim(" Stop: ") + chalk.cyan("sudo systemctl stop jive-task-runner"));
4482
+ else console.log(chalk.dim(" Start: ") + chalk.cyan("sudo systemctl start jive-task-runner"));
4283
4483
  console.log(chalk.dim(" Uninstall: ") + chalk.cyan("jive task-runner uninstall-service"));
4284
4484
  console.log();
4285
4485
  } catch (error$1) {
@@ -4292,7 +4492,7 @@ async function serviceStatusCommand() {
4292
4492
  */
4293
4493
  async function serviceLogsCommand(options) {
4294
4494
  try {
4295
- const { getServiceManager } = await import("./service-4H4YceKv.mjs");
4495
+ const { getServiceManager } = await import("./service-MMjLsA9C.mjs");
4296
4496
  const manager = getServiceManager();
4297
4497
  if (!await manager.isInstalled()) {
4298
4498
  console.log(chalk.dim("Service is not installed."));
@@ -4314,7 +4514,7 @@ async function serviceLogsCommand(options) {
4314
4514
  */
4315
4515
  async function serviceRestartCommand() {
4316
4516
  try {
4317
- const { getServiceManager } = await import("./service-4H4YceKv.mjs");
4517
+ const { getServiceManager } = await import("./service-MMjLsA9C.mjs");
4318
4518
  const manager = getServiceManager();
4319
4519
  if (!await manager.isInstalled()) {
4320
4520
  console.log(chalk.dim("Service is not installed."));
@@ -2,21 +2,31 @@ import { E as WS_URL, T as GRAPHQL_API_URL, w as API_URL } from "./index.mjs";
2
2
  import fs from "fs/promises";
3
3
  import path from "path";
4
4
  import os from "os";
5
- import { exec, spawn } from "child_process";
5
+ import { exec, spawn, spawnSync } from "child_process";
6
6
  import { promisify } from "util";
7
7
 
8
8
  //#region src/lib/service/systemd.ts
9
9
  const execAsync$1 = promisify(exec);
10
+ const SERVICE_NAME = "jive-task-runner";
11
+ const SYSTEM_SERVICE_PATH = `/etc/systemd/system/${SERVICE_NAME}.service`;
12
+ const USER_SERVICE_DIR = path.join(os.homedir(), ".config", "systemd", "user");
13
+ const LEGACY_USER_SERVICE_PATH = path.join(USER_SERVICE_DIR, `${SERVICE_NAME}.service`);
14
+ const ENV_DIR = "/etc/jive";
15
+ const ENV_FILE_PATH = `${ENV_DIR}/runner.env`;
10
16
  const SERVICE_TEMPLATE = `[Unit]
11
17
  Description=Jive Task Runner
12
18
  Documentation=https://getjive.app/docs
13
- After=network-online.target
19
+ After=network-online.target docker.service
14
20
  Wants=network-online.target
21
+ Requires=docker.service
15
22
 
16
23
  [Service]
17
24
  Type=simple
25
+ User={{SERVICE_USER}}
26
+ Group={{SERVICE_GROUP}}
27
+ WorkingDirectory={{WORKING_DIRECTORY}}
18
28
  ExecStart={{JIVE_BINARY_PATH}} task-runner start
19
- Restart=on-failure
29
+ Restart=always
20
30
  RestartSec=30
21
31
  TimeoutStartSec=90
22
32
  TimeoutStopSec=30
@@ -24,13 +34,10 @@ StartLimitBurst=5
24
34
  StartLimitIntervalSec=10m
25
35
  KillMode=mixed
26
36
  Environment="PATH={{NODE_BIN_PATH}}:/usr/local/bin:/usr/bin:/bin"
27
- Environment="JIVE_API_KEY={{JIVE_API_KEY}}"
28
- Environment="ANTHROPIC_API_KEY={{ANTHROPIC_API_KEY}}"
29
- Environment="JIVE_TEAM_ID={{JIVE_TEAM_ID}}"
30
- Environment="JIVE_RUNNER_ID={{JIVE_RUNNER_ID}}"
31
37
  Environment="JIVE_API_URL={{JIVE_API_URL}}"
32
38
  Environment="JIVE_WS_URL={{JIVE_WS_URL}}"
33
39
  Environment="JIVE_GRAPHQL_API_URL={{JIVE_GRAPHQL_API_URL}}"
40
+ EnvironmentFile={{ENV_FILE_PATH}}
34
41
 
35
42
  StandardOutput=journal
36
43
  StandardError=journal
@@ -43,16 +50,64 @@ ProtectKernelTunables=true
43
50
  RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
44
51
 
45
52
  [Install]
46
- WantedBy=default.target
53
+ WantedBy=multi-user.target
47
54
  `;
55
+ /**
56
+ * Check if the current process is running as root (UID 0)
57
+ */
58
+ function isRunningAsRoot() {
59
+ return process.getuid?.() === 0;
60
+ }
61
+ /**
62
+ * Re-execute the current command with sudo, preserving PATH and environment.
63
+ * This allows users to just run `jive task-runner install-service` without
64
+ * needing to manually invoke sudo with the correct environment.
65
+ */
66
+ function reExecWithSudo() {
67
+ const nodePath = process.execPath;
68
+ const scriptPath = process.argv[1];
69
+ const args = process.argv.slice(2);
70
+ console.log("Root privileges required. Re-running with sudo...\n");
71
+ const result = spawnSync("sudo", [
72
+ "--preserve-env=PATH,HOME",
73
+ `SUDO_USER=${process.env.USER}`,
74
+ `SUDO_UID=${process.getuid?.() || 1e3}`,
75
+ `SUDO_GID=${process.getgid?.() || 1e3}`,
76
+ nodePath,
77
+ scriptPath,
78
+ ...args
79
+ ], {
80
+ stdio: "inherit",
81
+ env: process.env
82
+ });
83
+ process.exit(result.status ?? 1);
84
+ }
85
+ /**
86
+ * Get the original user info when running with sudo
87
+ * Returns the user who invoked sudo, not root
88
+ */
89
+ function getCurrentUser() {
90
+ return {
91
+ uid: parseInt(process.env.SUDO_UID || String(process.getuid?.() || 1e3), 10),
92
+ gid: parseInt(process.env.SUDO_GID || String(process.getgid?.() || 1e3), 10),
93
+ username: process.env.SUDO_USER || process.env.USER || "jive",
94
+ homeDir: process.env.SUDO_USER ? `/home/${process.env.SUDO_USER}` : os.homedir()
95
+ };
96
+ }
48
97
  var SystemdServiceManager = class {
49
- servicePath;
50
- serviceName = "jive-task-runner";
51
- constructor() {
52
- const homeDir = os.homedir();
53
- this.servicePath = path.join(homeDir, ".config", "systemd", "user", `${this.serviceName}.service`);
98
+ servicePath = SYSTEM_SERVICE_PATH;
99
+ serviceName = SERVICE_NAME;
100
+ /**
101
+ * Check for legacy user service and handle migration.
102
+ * Call this BEFORE starting any spinners since it may prompt the user.
103
+ */
104
+ async checkAndMigrateLegacyService() {
105
+ if (!isRunningAsRoot()) reExecWithSudo();
106
+ await this.migrateFromUserService();
54
107
  }
55
108
  async install() {
109
+ if (!isRunningAsRoot()) reExecWithSudo();
110
+ const user = getCurrentUser();
56
111
  const { getRunnerConfig } = await import("./tasks-Py86q1u7.mjs");
57
112
  const { getCredentials } = await import("./config-7rVDmj2u.mjs");
58
113
  const runnerConfig = await getRunnerConfig();
@@ -72,41 +127,86 @@ var SystemdServiceManager = class {
72
127
  if (resolvedPath.includes(pattern)) throw new Error(`Detected unstable path for jive binary: ${resolvedPath}\nThis path contains '${pattern}' which may not persist across reboots.\n\nIf you're using fnm, try:\n 1. Run: fnm exec --using=default -- npm install -g @jive-ai/cli\n 2. Then run install-service again from a fresh terminal`);
73
128
  if (resolvedNodePath.includes(pattern)) throw new Error(`Detected unstable path for node binary: ${resolvedNodePath}\nThis path contains '${pattern}' which may not persist across reboots.\n\nIf you're using fnm, ensure you have a default node version set:\n fnm default <version>`);
74
129
  }
75
- const variables = {
76
- JIVE_BINARY_PATH: resolvedPath,
77
- NODE_BIN_PATH: nodeBinDir,
130
+ await this.createEnvironmentFile({
78
131
  JIVE_API_KEY: credentials.token,
79
132
  ANTHROPIC_API_KEY: credentials.anthropicApiKey || "",
80
133
  JIVE_TEAM_ID: runnerConfig.teamId,
81
- JIVE_RUNNER_ID: runnerConfig.id.toString(),
134
+ JIVE_RUNNER_ID: runnerConfig.id.toString()
135
+ });
136
+ const variables = {
137
+ SERVICE_USER: user.username,
138
+ SERVICE_GROUP: user.username,
139
+ WORKING_DIRECTORY: user.homeDir,
140
+ JIVE_BINARY_PATH: resolvedPath,
141
+ NODE_BIN_PATH: nodeBinDir,
82
142
  JIVE_API_URL: process.env.JIVE_API_URL || API_URL,
83
143
  JIVE_WS_URL: process.env.JIVE_WS_URL || WS_URL,
84
- JIVE_GRAPHQL_API_URL: process.env.JIVE_GRAPHQL_API_URL || GRAPHQL_API_URL
144
+ JIVE_GRAPHQL_API_URL: process.env.JIVE_GRAPHQL_API_URL || GRAPHQL_API_URL,
145
+ ENV_FILE_PATH
85
146
  };
86
147
  let serviceContent = SERVICE_TEMPLATE;
87
148
  for (const [key, value] of Object.entries(variables)) serviceContent = serviceContent.replace(new RegExp(`{{${key}}}`, "g"), value);
88
- const serviceDir = path.dirname(this.servicePath);
89
- await fs.mkdir(serviceDir, {
90
- recursive: true,
91
- mode: 493
92
- });
93
- const dirMode = (await fs.stat(serviceDir)).mode & 511;
94
- if (dirMode > 493) throw new Error(`Systemd user directory has overly permissive permissions: ${dirMode.toString(8)}\nExpected 0755 or stricter. Fix with: chmod 755 ${serviceDir}`);
95
- await fs.writeFile(this.servicePath, serviceContent, { mode: 384 });
149
+ await fs.writeFile(this.servicePath, serviceContent, { mode: 420 });
96
150
  try {
97
- await execAsync$1("systemctl --user daemon-reload", { timeout: 3e4 });
98
- await execAsync$1(`systemctl --user enable ${this.serviceName}`, { timeout: 3e4 });
151
+ await execAsync$1("systemctl daemon-reload", { timeout: 3e4 });
152
+ await execAsync$1(`systemctl enable ${this.serviceName}`, { timeout: 3e4 });
99
153
  } catch (error) {
100
154
  try {
101
155
  await fs.unlink(this.servicePath);
102
- await execAsync$1("systemctl --user daemon-reload", { timeout: 3e4 });
156
+ await fs.unlink(ENV_FILE_PATH);
157
+ await execAsync$1("systemctl daemon-reload", { timeout: 3e4 });
103
158
  } catch (cleanupError) {
104
159
  console.error("Failed to clean up after installation failure:", cleanupError);
105
160
  }
106
161
  throw new Error(`Service installation failed: ${error.message}\nPartial installation has been rolled back.`);
107
162
  }
108
163
  }
164
+ /**
165
+ * Create the environment file with sensitive credentials
166
+ */
167
+ async createEnvironmentFile(vars) {
168
+ await fs.mkdir(ENV_DIR, {
169
+ recursive: true,
170
+ mode: 493
171
+ });
172
+ const content = Object.entries(vars).map(([key, value]) => `${key}=${value}`).join("\n") + "\n";
173
+ await fs.writeFile(ENV_FILE_PATH, content, { mode: 384 });
174
+ }
175
+ /**
176
+ * Check for and migrate from legacy user service
177
+ */
178
+ async migrateFromUserService() {
179
+ try {
180
+ await fs.access(LEGACY_USER_SERVICE_PATH);
181
+ } catch {
182
+ return;
183
+ }
184
+ const { default: prompts } = await import("prompts");
185
+ console.log("\n⚠ Found existing user service at:");
186
+ console.log(` ${LEGACY_USER_SERVICE_PATH}\n`);
187
+ const { migrate } = await prompts({
188
+ type: "confirm",
189
+ name: "migrate",
190
+ message: "Migrate to system service? (This will remove the old user service)",
191
+ initial: true
192
+ });
193
+ if (!migrate) throw new Error("Migration cancelled. Remove the user service first or choose to migrate.");
194
+ const user = getCurrentUser();
195
+ console.log("Stopping and removing legacy user service...");
196
+ try {
197
+ await execAsync$1(`sudo -u ${user.username} systemctl --user stop ${this.serviceName}`, { timeout: 3e4 });
198
+ } catch {}
199
+ try {
200
+ await execAsync$1(`sudo -u ${user.username} systemctl --user disable ${this.serviceName}`, { timeout: 3e4 });
201
+ } catch {}
202
+ await fs.unlink(LEGACY_USER_SERVICE_PATH);
203
+ try {
204
+ await execAsync$1(`sudo -u ${user.username} systemctl --user daemon-reload`, { timeout: 3e4 });
205
+ } catch {}
206
+ console.log("Legacy user service removed successfully.\n");
207
+ }
109
208
  async uninstall() {
209
+ if (!isRunningAsRoot()) reExecWithSudo();
110
210
  try {
111
211
  await this.stop();
112
212
  } catch (error) {
@@ -114,7 +214,7 @@ var SystemdServiceManager = class {
114
214
  else console.warn(`Warning: Failed to stop service: ${error.message}`);
115
215
  }
116
216
  try {
117
- await execAsync$1(`systemctl --user disable ${this.serviceName}`, { timeout: 3e4 });
217
+ await execAsync$1(`systemctl disable ${this.serviceName}`, { timeout: 3e4 });
118
218
  } catch (error) {
119
219
  if (error.stderr?.includes("No such file") || error.message?.includes("not be found")) {} else if (error.code === "EACCES") console.warn("Warning: Permission denied when disabling service");
120
220
  else console.warn(`Warning: Failed to disable service: ${error.message}`);
@@ -124,16 +224,24 @@ var SystemdServiceManager = class {
124
224
  } catch (error) {
125
225
  if (error.code !== "ENOENT") throw new Error(`Failed to remove service file: ${error.message}`);
126
226
  }
127
- await execAsync$1("systemctl --user daemon-reload", { timeout: 3e4 });
227
+ try {
228
+ await fs.unlink(ENV_FILE_PATH);
229
+ } catch (error) {
230
+ if (error.code !== "ENOENT") console.warn(`Warning: Failed to remove environment file: ${error.message}`);
231
+ }
232
+ try {
233
+ await fs.rmdir(ENV_DIR);
234
+ } catch {}
235
+ await execAsync$1("systemctl daemon-reload", { timeout: 3e4 });
128
236
  }
129
237
  async start() {
130
- await execAsync$1(`systemctl --user start ${this.serviceName}`, { timeout: 3e4 });
238
+ await execAsync$1(`systemctl start ${this.serviceName}`, { timeout: 3e4 });
131
239
  }
132
240
  async stop() {
133
- await execAsync$1(`systemctl --user stop ${this.serviceName}`, { timeout: 3e4 });
241
+ await execAsync$1(`systemctl stop ${this.serviceName}`, { timeout: 3e4 });
134
242
  }
135
243
  async restart() {
136
- await execAsync$1(`systemctl --user restart ${this.serviceName}`, { timeout: 3e4 });
244
+ await execAsync$1(`systemctl restart ${this.serviceName}`, { timeout: 3e4 });
137
245
  }
138
246
  async status() {
139
247
  if (!await this.isInstalled()) return {
@@ -142,11 +250,11 @@ var SystemdServiceManager = class {
142
250
  enabled: false
143
251
  };
144
252
  try {
145
- const { stdout } = await execAsync$1(`systemctl --user status ${this.serviceName} --no-pager`, { timeout: 3e4 });
253
+ const { stdout } = await execAsync$1(`systemctl status ${this.serviceName} --no-pager`, { timeout: 3e4 });
146
254
  const running = stdout.includes("Active: active (running)");
147
255
  const pid = this.extractPid(stdout);
148
256
  const uptime = this.extractUptime(stdout);
149
- const { stdout: isEnabledOutput } = await execAsync$1(`systemctl --user is-enabled ${this.serviceName}`, { timeout: 3e4 });
257
+ const { stdout: isEnabledOutput } = await execAsync$1(`systemctl is-enabled ${this.serviceName}`, { timeout: 3e4 });
150
258
  return {
151
259
  installed: true,
152
260
  running,
@@ -155,7 +263,7 @@ var SystemdServiceManager = class {
155
263
  pid
156
264
  };
157
265
  } catch (error) {
158
- const { stdout: isEnabledOutput } = await execAsync$1(`systemctl --user is-enabled ${this.serviceName}`, { timeout: 3e4 }).catch(() => ({ stdout: "disabled" }));
266
+ const { stdout: isEnabledOutput } = await execAsync$1(`systemctl is-enabled ${this.serviceName}`, { timeout: 3e4 }).catch(() => ({ stdout: "disabled" }));
159
267
  return {
160
268
  installed: true,
161
269
  running: false,
@@ -164,11 +272,7 @@ var SystemdServiceManager = class {
164
272
  }
165
273
  }
166
274
  async logs(options) {
167
- const args = [
168
- "--user",
169
- "-u",
170
- this.serviceName
171
- ];
275
+ const args = ["-u", this.serviceName];
172
276
  if (options?.follow) args.push("-f");
173
277
  if (options?.lines) args.push("-n", options.lines.toString());
174
278
  const logsProcess = spawn("journalctl", args, { stdio: "inherit" });
@@ -240,6 +344,18 @@ async function validateServiceInstallation() {
240
344
  const checks = [];
241
345
  let canInstall = true;
242
346
  let hasWarnings = false;
347
+ if (!isRunningAsRoot()) {
348
+ checks.push({
349
+ name: "Root privileges",
350
+ status: "warning",
351
+ message: "Will prompt for sudo password"
352
+ });
353
+ hasWarnings = true;
354
+ } else checks.push({
355
+ name: "Root privileges",
356
+ status: "success",
357
+ message: "Running as root"
358
+ });
243
359
  try {
244
360
  const { getRunnerConfig } = await import("./tasks-Py86q1u7.mjs");
245
361
  const runnerConfig = await getRunnerConfig();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@jive-ai/cli",
4
- "version": "0.0.45",
4
+ "version": "0.0.46",
5
5
  "main": "index.js",
6
6
  "files": [
7
7
  "dist",
@@ -15,7 +15,8 @@
15
15
  "test": "echo \"Error: no test specified\" && exit 1",
16
16
  "typecheck": "tsc --noEmit",
17
17
  "build": "tsdown && npm pack && npm install -g jive-ai-cli-*.tgz",
18
- "docker:build": "bun run build && .docker/build.sh",
18
+ "docker:clean": "docker rmi jiveai/task:latest jiveai/task:$npm_package_version",
19
+ "docker:build": "bun run build && npm run docker:clean && .docker/build.sh",
19
20
  "docker:push": ".docker/build.sh --push",
20
21
  "prepublishOnly": "npm run typecheck && npm run build"
21
22
  },