@jaibber/sdk 0.2.0 → 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;
@@ -948,6 +1037,10 @@ var JaibberAgent = class extends EventEmitter {
948
1037
  }
949
1038
  if (payload.isTaskNotification) return;
950
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
+ }
951
1044
  this.addToHistory(project.id, {
952
1045
  sender: payload.isAgentMessage ? "agent" : "user",
953
1046
  senderName: payload.fromUsername,
@@ -975,8 +1068,7 @@ var JaibberAgent = class extends EventEmitter {
975
1068
  const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
976
1069
  if (depth >= maxDepth) return false;
977
1070
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
978
- const mentions = parseMentions(text);
979
- if (mentions.length > 0 && !mentionsAgent(text, this.config.agentName)) return false;
1071
+ if (!mentionsAgent(text, this.config.agentName)) return false;
980
1072
  return true;
981
1073
  }
982
1074
  async respondToMessage(payload, project, incomingDepth, incomingChain) {
@@ -1014,10 +1106,12 @@ var JaibberAgent = class extends EventEmitter {
1014
1106
  return;
1015
1107
  }
1016
1108
  if (this.provider) {
1109
+ this.updateProviderSession(project.id);
1017
1110
  const systemPrompt = this.config.agentInstructions ?? "";
1018
1111
  await ctx.stream(
1019
1112
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1020
1113
  );
1114
+ this.captureProviderSession(project.id);
1021
1115
  return;
1022
1116
  }
1023
1117
  console.warn(
@@ -1070,6 +1164,7 @@ var JaibberAgent = class extends EventEmitter {
1070
1164
  return;
1071
1165
  }
1072
1166
  if (this.provider) {
1167
+ this.updateProviderSession(project.id);
1073
1168
  const taskPrompt = task.description ? `Task: ${task.title}
1074
1169
 
1075
1170
  ${task.description}` : `Task: ${task.title}`;
@@ -1094,6 +1189,7 @@ ${task.description}` : `Task: ${task.title}`;
1094
1189
  conversationHistory
1095
1190
  )
1096
1191
  );
1192
+ this.captureProviderSession(project.id);
1097
1193
  await this.client.updateTask(task.id, { status: "completed" });
1098
1194
  } catch {
1099
1195
  await this.client.updateTask(task.id, { status: "failed" });
@@ -1111,6 +1207,27 @@ ${task.description}` : `Task: ${task.title}`;
1111
1207
  }
1112
1208
  }
1113
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
+ }
1114
1231
  // ── Conversation history ────────────────────────────────────────────
1115
1232
  async loadHistory(projectId) {
1116
1233
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
@@ -1160,6 +1277,57 @@ import { writeFileSync, mkdirSync } from "fs";
1160
1277
  import { execSync } from "child_process";
1161
1278
  import { homedir } from "os";
1162
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
1163
1331
  function parseArgs(argv) {
1164
1332
  const args2 = {};
1165
1333
  for (let i = 0; i < argv.length; i++) {
@@ -1200,6 +1368,8 @@ OPTIONAL:
1200
1368
  --register Create a new account (instead of logging into an existing one)
1201
1369
  --create-project <name> Create a new project and join it (prints project ID on start)
1202
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
1203
1373
  --server <url> Server URL (default: https://api.jaibber.com)
1204
1374
  --instructions <text> System prompt for the agent
1205
1375
  --machine-name <name> Machine identifier shown in presence
@@ -1255,16 +1425,31 @@ ENVIRONMENT VARIABLES:
1255
1425
  `);
1256
1426
  process.exit(0);
1257
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
+ }
1258
1443
  var username = args["username"];
1259
1444
  var password = args["password"] || process.env.JAIBBER_PASSWORD;
1260
- var agentName = args["agent-name"];
1445
+ var agentName = args["agent-name"] || template?.agentName;
1261
1446
  var serverUrl = args["server"] || "https://api.jaibber.com";
1262
1447
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1263
1448
  var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1264
1449
  var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
1265
1450
  var useClaudeCli = args["claude-cli"] === "true";
1266
1451
  var projectDir = args["project-dir"];
1267
- var instructions = args["instructions"];
1452
+ var instructions = args["instructions"] || template?.instructions;
1268
1453
  var machineName = args["machine-name"];
1269
1454
  var shouldRegister = args["register"] === "true";
1270
1455
  var createProjectName = args["create-project"];