@jaibber/sdk 0.1.9 → 0.3.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.
package/README.md CHANGED
@@ -1,70 +1,70 @@
1
- # @jaibber/sdk
2
-
3
- Headless agent SDK for [Jaibber](https://jaibber.com) — run AI agents without a desktop app.
4
-
5
- ## Quick Start
6
-
7
- ```bash
8
- npx @jaibber/sdk \
9
- --username bot \
10
- --password secret \
11
- --agent-name Coder \
12
- --project myproject
13
- ```
14
-
15
- Or install globally:
16
-
17
- ```bash
18
- npm install -g @jaibber/sdk
19
- jaibber-agent --username bot --password secret --agent-name Coder
20
- ```
21
-
22
- ## Programmatic Usage
23
-
24
- ```typescript
25
- import { JaibberAgent, AnthropicProvider } from "@jaibber/sdk";
26
-
27
- const agent = new JaibberAgent({
28
- apiBaseUrl: "https://api.jaibber.com",
29
- username: "bot",
30
- password: "secret",
31
- agentName: "Coder",
32
- provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
33
- });
34
-
35
- agent.onMessage(async (ctx) => {
36
- const stream = await ctx.provider.stream(ctx.messages);
37
- await ctx.stream(stream);
38
- });
39
-
40
- agent.onTask(async (ctx) => {
41
- await ctx.complete("Task done!");
42
- });
43
-
44
- await agent.start();
45
- ```
46
-
47
- ## Environment Variables
48
-
49
- | Variable | Description |
50
- |----------|-------------|
51
- | `ANTHROPIC_API_KEY` | Anthropic API key for Claude |
52
- | `JAIBBER_PASSWORD` | Password (alternative to `--password` flag) |
53
-
54
- ## Features
55
-
56
- - Real-time streaming via Ably WebSocket
57
- - @mention routing — only responds when addressed
58
- - Task auto-execution (submitted → working → completed/failed)
59
- - Conversation context (last 20 messages)
60
- - Loop prevention (max depth 3)
61
- - Graceful shutdown on SIGINT/SIGTERM
62
- - Dual-write: responses published to both Ably and REST API
63
-
64
- ## Documentation
65
-
66
- Full docs at [jaibber.com/guide/sdk](https://jaibber.com/guide/sdk)
67
-
68
- ## License
69
-
70
- MIT
1
+ # @jaibber/sdk
2
+
3
+ Headless agent SDK for [Jaibber](https://jaibber.com) — run AI agents without a desktop app.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ npx @jaibber/sdk \
9
+ --username bot \
10
+ --password secret \
11
+ --agent-name Coder \
12
+ --project myproject
13
+ ```
14
+
15
+ Or install globally:
16
+
17
+ ```bash
18
+ npm install -g @jaibber/sdk
19
+ jaibber-agent --username bot --password secret --agent-name Coder
20
+ ```
21
+
22
+ ## Programmatic Usage
23
+
24
+ ```typescript
25
+ import { JaibberAgent, AnthropicProvider } from "@jaibber/sdk";
26
+
27
+ const agent = new JaibberAgent({
28
+ apiBaseUrl: "https://api.jaibber.com",
29
+ username: "bot",
30
+ password: "secret",
31
+ agentName: "Coder",
32
+ provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
33
+ });
34
+
35
+ agent.onMessage(async (ctx) => {
36
+ const stream = await ctx.provider.stream(ctx.messages);
37
+ await ctx.stream(stream);
38
+ });
39
+
40
+ agent.onTask(async (ctx) => {
41
+ await ctx.complete("Task done!");
42
+ });
43
+
44
+ await agent.start();
45
+ ```
46
+
47
+ ## Environment Variables
48
+
49
+ | Variable | Description |
50
+ |----------|-------------|
51
+ | `ANTHROPIC_API_KEY` | Anthropic API key for Claude |
52
+ | `JAIBBER_PASSWORD` | Password (alternative to `--password` flag) |
53
+
54
+ ## Features
55
+
56
+ - Real-time streaming via Ably WebSocket
57
+ - @mention routing — only responds when addressed
58
+ - Task auto-execution (submitted → working → completed/failed)
59
+ - Conversation context (last 20 messages)
60
+ - Loop prevention (max depth 3)
61
+ - Graceful shutdown on SIGINT/SIGTERM
62
+ - Dual-write: responses published to both Ably and REST API
63
+
64
+ ## Documentation
65
+
66
+ Full docs at [jaibber.com/guide/sdk](https://jaibber.com/guide/sdk)
67
+
68
+ ## License
69
+
70
+ MIT
package/dist/cli.js CHANGED
@@ -149,6 +149,23 @@ var JaibberClient = class {
149
149
  return data.data;
150
150
  }
151
151
  // ── Tasks ───────────────────────────────────────────────────────────
152
+ /** POST /api/projects/{id}/tasks — create a task. */
153
+ async createTask(projectId, data) {
154
+ const res = await fetch(
155
+ `${this.serverUrl}/api/projects/${projectId}/tasks`,
156
+ {
157
+ method: "POST",
158
+ headers: this.authHeaders(),
159
+ body: JSON.stringify(data)
160
+ }
161
+ );
162
+ if (!res.ok) {
163
+ const text = await res.text();
164
+ throw new Error(`Failed to create task (${res.status}): ${text}`);
165
+ }
166
+ const result = await res.json();
167
+ return result.data;
168
+ }
152
169
  /** PATCH /api/tasks/{taskId} — update task fields. */
153
170
  async updateTask(taskId, updates) {
154
171
  const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
@@ -186,7 +203,11 @@ var AblyManager = class {
186
203
  callback(err, null);
187
204
  }
188
205
  },
189
- clientId: this.userId
206
+ clientId: this.userId,
207
+ disconnectedRetryTimeout: 5e3,
208
+ // 5s initial retry on disconnect
209
+ suspendedRetryTimeout: 3e4
210
+ // 30s retry when suspended
190
211
  });
191
212
  this.ably.connection.once("connected", () => {
192
213
  resolve();
@@ -198,6 +219,17 @@ var AblyManager = class {
198
219
  )
199
220
  );
200
221
  });
222
+ this.ably.connection.on("disconnected", () => {
223
+ console.warn("[sdk] Ably disconnected, will retry...");
224
+ });
225
+ this.ably.connection.on("suspended", () => {
226
+ console.warn("[sdk] Ably connection suspended (extended outage)");
227
+ });
228
+ this.ably.connection.on("connected", () => {
229
+ if (this.channels.size > 0) {
230
+ console.log("[sdk] Ably reconnected");
231
+ }
232
+ });
201
233
  });
202
234
  }
203
235
  /** Enter global presence channel (jaibber:presence). */
@@ -459,6 +491,18 @@ var TaskContext = class {
459
491
  }).catch((err) => console.error("[sdk] Failed to persist:", err));
460
492
  }
461
493
  }
494
+ /**
495
+ * Create a follow-up task assigned to another agent.
496
+ * Automatically sets parentTaskId to the current task's ID.
497
+ */
498
+ async createFollowUpTask(data) {
499
+ return this.client.createTask(this.projectId, {
500
+ ...data,
501
+ parentTaskId: this.task.id,
502
+ createdByType: "agent",
503
+ createdByName: this.agentName
504
+ });
505
+ }
462
506
  /** Send a chat message (for progress updates). */
463
507
  async sendMessage(text) {
464
508
  const msgId = uuidv4();
@@ -483,13 +527,6 @@ var TaskContext = class {
483
527
  };
484
528
 
485
529
  // src/mentions.ts
486
- function parseMentions(text) {
487
- const mentions = [];
488
- for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
489
- mentions.push(match[1].toLowerCase());
490
- }
491
- return mentions;
492
- }
493
530
  function mentionsAgent(text, agentName2) {
494
531
  const pattern = new RegExp(`@${escapeRegex(agentName2)}(?!\\w)`, "i");
495
532
  return pattern.test(text);
@@ -775,10 +812,28 @@ var GoogleProvider = class {
775
812
 
776
813
  // src/providers/claude-cli.ts
777
814
  import { spawn } from "child_process";
815
+ import { createInterface } from "readline";
778
816
  var ClaudeCLIProvider = class {
779
817
  projectDir;
818
+ sessionId;
819
+ continueSession;
820
+ /** Last session ID captured from Claude CLI stream-json output. */
821
+ lastSessionId;
780
822
  constructor(options = {}) {
781
823
  this.projectDir = options.projectDir ?? process.cwd();
824
+ this.sessionId = options.sessionId;
825
+ this.continueSession = options.continueSession ?? false;
826
+ }
827
+ /** Update session ID for future --resume calls. */
828
+ setSessionId(id) {
829
+ this.sessionId = id;
830
+ this.continueSession = false;
831
+ }
832
+ /** Clear session state (e.g. on conversation clear). */
833
+ clearSession() {
834
+ this.sessionId = void 0;
835
+ this.lastSessionId = void 0;
836
+ this.continueSession = false;
782
837
  }
783
838
  async *generate(prompt, systemPrompt, conversationContext) {
784
839
  let fullPrompt = "";
@@ -794,7 +849,15 @@ ${systemPrompt}
794
849
  fullPrompt += "\n\n---\n\n";
795
850
  }
796
851
  fullPrompt += prompt;
797
- const child = spawn("claude", ["--print", "--dangerously-skip-permissions"], {
852
+ const args2 = ["--print", "--output-format", "stream-json", "--dangerously-skip-permissions"];
853
+ if (this.sessionId) {
854
+ if (/^[a-zA-Z0-9-]+$/.test(this.sessionId)) {
855
+ args2.push("--resume", this.sessionId);
856
+ }
857
+ } else if (this.continueSession) {
858
+ args2.push("--continue");
859
+ }
860
+ const child = spawn("claude", args2, {
798
861
  cwd: this.projectDir,
799
862
  stdio: ["pipe", "pipe", "pipe"],
800
863
  shell: false
@@ -805,16 +868,40 @@ ${systemPrompt}
805
868
  child.stderr?.on("data", (chunk) => {
806
869
  stderr += chunk.toString();
807
870
  });
808
- const stdout = child.stdout;
809
- for await (const chunk of stdout) {
810
- const text = chunk.toString();
811
- if (text) yield text;
871
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
872
+ let gotOutput = false;
873
+ for await (const line of rl) {
874
+ try {
875
+ const json = JSON.parse(line);
876
+ if (json.session_id && typeof json.session_id === "string") {
877
+ this.lastSessionId = json.session_id;
878
+ }
879
+ if (json.delta?.text) {
880
+ gotOutput = true;
881
+ yield json.delta.text;
882
+ continue;
883
+ }
884
+ const content = json.content ?? json.message?.content;
885
+ if (Array.isArray(content)) {
886
+ for (const item of content) {
887
+ if (item.type === "text" && item.text) {
888
+ gotOutput = true;
889
+ yield item.text;
890
+ }
891
+ }
892
+ }
893
+ } catch {
894
+ if (line.trim()) {
895
+ gotOutput = true;
896
+ yield line + "\n";
897
+ }
898
+ }
812
899
  }
813
900
  const exitCode = await new Promise((resolve) => {
814
901
  child.on("close", resolve);
815
902
  });
816
903
  if (exitCode !== 0 && exitCode !== null) {
817
- if (!stderr.trim()) return;
904
+ if (gotOutput || !stderr.trim()) return;
818
905
  throw new Error(`Claude CLI exited with code ${exitCode}: ${stderr.trim()}`);
819
906
  }
820
907
  }
@@ -838,6 +925,8 @@ var JaibberAgent = class extends EventEmitter {
838
925
  history = /* @__PURE__ */ new Map();
839
926
  /** Track in-flight responses to prevent double-handling. */
840
927
  activeResponses = /* @__PURE__ */ new Set();
928
+ /** Session IDs per project for Claude --resume. */
929
+ sessionIds = /* @__PURE__ */ new Map();
841
930
  constructor(config) {
842
931
  super();
843
932
  this.config = config;
@@ -937,8 +1026,21 @@ var JaibberAgent = class extends EventEmitter {
937
1026
  // ── Message handling ────────────────────────────────────────────────
938
1027
  async handleIncomingMessage(payload, project) {
939
1028
  if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
1029
+ if (payload.type === "deregister") {
1030
+ const targetName = payload.agentName?.toLowerCase();
1031
+ if (!targetName || targetName === this.config.agentName.toLowerCase()) {
1032
+ console.log(`[sdk] Received deregister command. Shutting down...`);
1033
+ await this.disconnect();
1034
+ process.exit(0);
1035
+ }
1036
+ return;
1037
+ }
940
1038
  if (payload.isTaskNotification) return;
941
1039
  if (payload.type !== "message" && payload.type !== "response") return;
1040
+ if (payload.text && payload.text.length > 1e5) {
1041
+ console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1042
+ return;
1043
+ }
942
1044
  this.addToHistory(project.id, {
943
1045
  sender: payload.isAgentMessage ? "agent" : "user",
944
1046
  senderName: payload.fromUsername,
@@ -966,8 +1068,7 @@ var JaibberAgent = class extends EventEmitter {
966
1068
  const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
967
1069
  if (depth >= maxDepth) return false;
968
1070
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
969
- const mentions = parseMentions(text);
970
- if (mentions.length > 0 && !mentionsAgent(text, this.config.agentName)) return false;
1071
+ if (!mentionsAgent(text, this.config.agentName)) return false;
971
1072
  return true;
972
1073
  }
973
1074
  async respondToMessage(payload, project, incomingDepth, incomingChain) {
@@ -1005,10 +1106,12 @@ var JaibberAgent = class extends EventEmitter {
1005
1106
  return;
1006
1107
  }
1007
1108
  if (this.provider) {
1109
+ this.updateProviderSession(project.id);
1008
1110
  const systemPrompt = this.config.agentInstructions ?? "";
1009
1111
  await ctx.stream(
1010
1112
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1011
1113
  );
1114
+ this.captureProviderSession(project.id);
1012
1115
  return;
1013
1116
  }
1014
1117
  console.warn(
@@ -1061,6 +1164,7 @@ var JaibberAgent = class extends EventEmitter {
1061
1164
  return;
1062
1165
  }
1063
1166
  if (this.provider) {
1167
+ this.updateProviderSession(project.id);
1064
1168
  const taskPrompt = task.description ? `Task: ${task.title}
1065
1169
 
1066
1170
  ${task.description}` : `Task: ${task.title}`;
@@ -1085,6 +1189,7 @@ ${task.description}` : `Task: ${task.title}`;
1085
1189
  conversationHistory
1086
1190
  )
1087
1191
  );
1192
+ this.captureProviderSession(project.id);
1088
1193
  await this.client.updateTask(task.id, { status: "completed" });
1089
1194
  } catch {
1090
1195
  await this.client.updateTask(task.id, { status: "failed" });
@@ -1102,6 +1207,27 @@ ${task.description}` : `Task: ${task.title}`;
1102
1207
  }
1103
1208
  }
1104
1209
  }
1210
+ // ── Session management (Claude --resume) ────────────────────────────
1211
+ /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
1212
+ updateProviderSession(projectId) {
1213
+ if (this.provider instanceof ClaudeCLIProvider) {
1214
+ const sid = this.sessionIds.get(projectId);
1215
+ if (sid) {
1216
+ this.provider.setSessionId(sid);
1217
+ } else {
1218
+ this.provider.clearSession();
1219
+ }
1220
+ }
1221
+ }
1222
+ /** After response, capture the session ID from ClaudeCLIProvider if available. */
1223
+ captureProviderSession(projectId) {
1224
+ if (this.provider instanceof ClaudeCLIProvider) {
1225
+ const sid = this.provider.lastSessionId;
1226
+ if (sid) {
1227
+ this.sessionIds.set(projectId, sid);
1228
+ }
1229
+ }
1230
+ }
1105
1231
  // ── Conversation history ────────────────────────────────────────────
1106
1232
  async loadHistory(projectId) {
1107
1233
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
@@ -1151,6 +1277,57 @@ import { writeFileSync, mkdirSync } from "fs";
1151
1277
  import { execSync } from "child_process";
1152
1278
  import { homedir } from "os";
1153
1279
  import { join } from "path";
1280
+
1281
+ // src/templates.ts
1282
+ var AGENT_TEMPLATES = [
1283
+ {
1284
+ id: "code-writer",
1285
+ name: "Code Writer",
1286
+ description: "General-purpose coding agent",
1287
+ agentName: "Coder",
1288
+ instructions: "You are a skilled software engineer. When given a coding task:\n- Write clean, well-structured code that follows the project's existing patterns\n- Keep changes minimal and focused on the request\n- If you need to read files for context, do so before making changes\n- Prefer editing existing files over creating new ones\n- Do not add unnecessary comments, type annotations, or refactoring beyond the scope of the task"
1289
+ },
1290
+ {
1291
+ id: "pr-reviewer",
1292
+ name: "PR Reviewer",
1293
+ description: "Reviews code changes, suggests improvements",
1294
+ agentName: "Reviewer",
1295
+ instructions: "You are a thorough code reviewer. When reviewing changes:\n- Focus on correctness, security, and maintainability\n- Point out potential bugs, edge cases, and performance issues\n- Suggest concrete improvements with code examples\n- Be direct and concise \u2014 no filler praise\n- If the code looks good, say so briefly"
1296
+ },
1297
+ {
1298
+ id: "test-writer",
1299
+ name: "Test Writer",
1300
+ description: "Generates tests for existing code",
1301
+ agentName: "Tester",
1302
+ instructions: "You are a testing specialist. When asked to write tests:\n- Match the project's existing test framework and patterns\n- Cover happy paths, edge cases, and error conditions\n- Write tests that are readable and self-documenting\n- Use descriptive test names that explain the expected behavior\n- Prefer integration tests over unit tests when testing API endpoints"
1303
+ },
1304
+ {
1305
+ id: "devops",
1306
+ name: "DevOps",
1307
+ description: "Infrastructure, deployment, CI/CD tasks",
1308
+ agentName: "DevOps",
1309
+ instructions: "You are a DevOps engineer. When working on infrastructure tasks:\n- Prioritize reliability and security over convenience\n- Use environment variables for secrets \u2014 never hardcode them\n- Write idempotent scripts and configurations\n- Document any manual steps that can't be automated"
1310
+ },
1311
+ {
1312
+ id: "bug-hunter",
1313
+ name: "Bug Hunter",
1314
+ description: "Analyzes errors, traces bugs, suggests fixes",
1315
+ agentName: "BugHunter",
1316
+ instructions: "You are a debugging specialist. When investigating bugs:\n- Start by reading error messages and stack traces carefully\n- Trace the execution path from the error back to the root cause\n- Look at recent changes that might have introduced the bug\n- Propose a minimal fix that addresses the root cause, not just the symptom"
1317
+ },
1318
+ {
1319
+ id: "architect",
1320
+ name: "Architect",
1321
+ description: "High-level design and refactoring guidance",
1322
+ agentName: "Architect",
1323
+ instructions: "You are a software architect. When advising on design:\n- Consider the existing codebase architecture before proposing changes\n- Favor simplicity over cleverness\n- Think about maintainability, testability, and team knowledge\n- Provide concrete file paths and code examples, not just abstract guidance"
1324
+ }
1325
+ ];
1326
+ function getTemplate(id) {
1327
+ return AGENT_TEMPLATES.find((t) => t.id === id);
1328
+ }
1329
+
1330
+ // src/cli.ts
1154
1331
  function parseArgs(argv) {
1155
1332
  const args2 = {};
1156
1333
  for (let i = 0; i < argv.length; i++) {
@@ -1191,6 +1368,8 @@ OPTIONAL:
1191
1368
  --register Create a new account (instead of logging into an existing one)
1192
1369
  --create-project <name> Create a new project and join it (prints project ID on start)
1193
1370
  --install-service Install as a systemd user service and start it (Linux only)
1371
+ --template <name> Use a preset agent template (sets agent-name + instructions)
1372
+ --list-templates Show available agent templates and exit
1194
1373
  --server <url> Server URL (default: https://api.jaibber.com)
1195
1374
  --instructions <text> System prompt for the agent
1196
1375
  --machine-name <name> Machine identifier shown in presence
@@ -1246,16 +1425,31 @@ ENVIRONMENT VARIABLES:
1246
1425
  `);
1247
1426
  process.exit(0);
1248
1427
  }
1428
+ if (args["list-templates"] === "true") {
1429
+ console.log("\nAvailable agent templates:\n");
1430
+ for (const t of AGENT_TEMPLATES) {
1431
+ console.log(` ${t.id.padEnd(14)} ${t.name} \u2014 ${t.description}`);
1432
+ }
1433
+ console.log(`
1434
+ Usage: npx @jaibber/sdk --template code-writer ...`);
1435
+ process.exit(0);
1436
+ }
1437
+ var templateId = args["template"];
1438
+ var template = templateId ? getTemplate(templateId) : void 0;
1439
+ if (templateId && !template) {
1440
+ console.error(`Error: unknown template "${templateId}". Use --list-templates to see options.`);
1441
+ process.exit(1);
1442
+ }
1249
1443
  var username = args["username"];
1250
1444
  var password = args["password"] || process.env.JAIBBER_PASSWORD;
1251
- var agentName = args["agent-name"];
1445
+ var agentName = args["agent-name"] || template?.agentName;
1252
1446
  var serverUrl = args["server"] || "https://api.jaibber.com";
1253
1447
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1254
1448
  var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1255
1449
  var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
1256
1450
  var useClaudeCli = args["claude-cli"] === "true";
1257
1451
  var projectDir = args["project-dir"];
1258
- var instructions = args["instructions"];
1452
+ var instructions = args["instructions"] || template?.instructions;
1259
1453
  var machineName = args["machine-name"];
1260
1454
  var shouldRegister = args["register"] === "true";
1261
1455
  var createProjectName = args["create-project"];
@@ -1339,7 +1533,8 @@ Environment=HOME=${homedir()}
1339
1533
  WantedBy=default.target
1340
1534
  `;
1341
1535
  const serviceDir = join(homedir(), ".config", "systemd", "user");
1342
- const serviceName = `jaibber-agent.service`;
1536
+ const serviceSlug = `jaibber-${agentName.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
1537
+ const serviceName = `${serviceSlug}.service`;
1343
1538
  const servicePath = join(serviceDir, serviceName);
1344
1539
  mkdirSync(serviceDir, { recursive: true });
1345
1540
  writeFileSync(servicePath, serviceContent);
@@ -1347,23 +1542,26 @@ WantedBy=default.target
1347
1542
  execSync(`systemctl --user daemon-reload`, { stdio: "ignore" });
1348
1543
  execSync(`systemctl --user enable --now ${serviceName}`, { stdio: "ignore" });
1349
1544
  console.log(`[cli] Service installed and started (systemd).`);
1350
- console.log(`[cli] systemctl --user status jaibber-agent`);
1351
- console.log(`[cli] systemctl --user restart jaibber-agent`);
1352
- console.log(`[cli] journalctl --user -u jaibber-agent -f`);
1545
+ console.log(`[cli] systemctl --user status ${serviceSlug}`);
1546
+ console.log(`[cli] systemctl --user restart ${serviceSlug}`);
1547
+ console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
1353
1548
  } catch {
1354
- const cronLine = `@reboot ${execStart} >> ${homedir()}/jaibber-agent.log 2>&1`;
1549
+ const logFile = `${homedir()}/${serviceSlug}.log`;
1550
+ const cronLine = `@reboot ${execStart} >> ${logFile} 2>&1`;
1551
+ const cronMarker = `jaibber:${serviceSlug}`;
1355
1552
  try {
1356
1553
  let existing = "";
1357
1554
  try {
1358
1555
  existing = execSync("crontab -l 2>/dev/null").toString();
1359
1556
  } catch {
1360
1557
  }
1361
- const filtered = existing.split("\n").filter((l) => !l.includes("jaibber-agent")).join("\n").trimEnd();
1362
- const newCrontab = (filtered ? filtered + "\n" : "") + cronLine + "\n";
1558
+ const filtered = existing.split("\n").filter((l) => !l.includes(cronMarker) && !l.includes(serviceSlug)).join("\n").trimEnd();
1559
+ const newCrontab = (filtered ? filtered + "\n" : "") + `# ${cronMarker}
1560
+ ` + cronLine + "\n";
1363
1561
  execSync(`echo ${JSON.stringify(newCrontab)} | crontab -`);
1364
1562
  console.log(`[cli] Service installed via crontab (starts on reboot).`);
1365
- console.log(`[cli] View log: tail -f ~/jaibber-agent.log`);
1366
- console.log(`[cli] Remove: crontab -e (delete the jaibber-agent line)`);
1563
+ console.log(`[cli] View log: tail -f ~/${serviceSlug}.log`);
1564
+ console.log(`[cli] Remove: crontab -e (delete the ${serviceSlug} lines)`);
1367
1565
  console.log(`[cli] Tip: run "sudo loginctl enable-linger ${process.env.USER || "ubuntu"}" to switch to systemd for better reliability.`);
1368
1566
  const { spawn: spawnBg } = await import("child_process");
1369
1567
  spawnBg(binaryPath, [scriptPath, ...flags], {
@@ -1374,7 +1572,7 @@ WantedBy=default.target
1374
1572
  } catch (cronErr) {
1375
1573
  console.error(`[cli] Could not install via crontab either: ${cronErr instanceof Error ? cronErr.message : cronErr}`);
1376
1574
  console.error(`[cli] Service file written to: ${servicePath}`);
1377
- console.error(`[cli] Run manually: sudo loginctl enable-linger $USER && systemctl --user enable --now jaibber-agent`);
1575
+ console.error(`[cli] Run manually: sudo loginctl enable-linger $USER && systemctl --user enable --now ${serviceSlug}`);
1378
1576
  process.exit(1);
1379
1577
  }
1380
1578
  }